mirror of
https://github.com/farion1231/cc-switch.git
synced 2026-07-25 05:38:38 +08:00
Compare commits
72 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 52f0ff3961 | |||
| 544e9bf937 | |||
| 48fb00d81b | |||
| 854266e3c4 | |||
| af8f907467 | |||
| 6a083cdd1c | |||
| c68476d0ea | |||
| 96a0a37331 | |||
| fb70f6d4b7 | |||
| fda88b2e42 | |||
| 8e2ffbc845 | |||
| 4f7ea76347 | |||
| 98c8255dbb | |||
| dbb943852d | |||
| cc070327ff | |||
| 67e074c0a7 | |||
| b1c7fe5563 | |||
| 210bff96c2 | |||
| 3b33e6921b | |||
| 8d5f72757e | |||
| 8cae7b7b73 | |||
| d61c24255b | |||
| b3bb020d3c | |||
| 31278e8916 | |||
| e9ead2841d | |||
| eaf83f4fbe | |||
| 90812e7f3a | |||
| 8c42ec48ef | |||
| 761038f0ea | |||
| 155a226e6a | |||
| 10be929f33 | |||
| 141010332b | |||
| 15989effb4 | |||
| d4edf30747 | |||
| 44b6eacf87 | |||
| 0a301a497c | |||
| 8aa6ec784b | |||
| bd3cfb7741 | |||
| 117dbf1386 | |||
| 72f570b99e | |||
| 2296c41497 | |||
| fe3f9b60de | |||
| 3e78fe8305 | |||
| 6f170305b8 | |||
| 552f7abee4 | |||
| fd2b232f1c | |||
| 82c75de51c | |||
| 8ccfbd36d6 | |||
| 36bbdc36f5 | |||
| fc08a5d364 | |||
| 333c9f277b | |||
| 9336001746 | |||
| 04254d6ffe | |||
| 28afbea917 | |||
| 81897ac17e | |||
| bb23ab918b | |||
| f38facd430 | |||
| 5c03de53f7 | |||
| d8a7bc32db | |||
| f1cad25777 | |||
| 9439153f05 | |||
| 7097a0d710 | |||
| f1d2c6045b | |||
| 9e5a3b2dc9 | |||
| 2466873db3 | |||
| 3c902b4599 | |||
| 1582d33705 | |||
| 305c0f2e08 | |||
| 8e1204b1ee | |||
| 3568c98f57 | |||
| 7ca33ff901 | |||
| e561084f62 |
+253
-23
@@ -150,9 +150,76 @@ jobs:
|
||||
fi
|
||||
echo "✅ Tauri signing key prepared"
|
||||
|
||||
- name: Import Apple signing certificate
|
||||
if: runner.os == 'macOS'
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# Decode .p12 certificate from base64
|
||||
CERT_PATH="$RUNNER_TEMP/certificate.p12"
|
||||
printf '%s' "${{ secrets.APPLE_CERTIFICATE }}" | (base64 --decode 2>/dev/null || base64 -D) > "$CERT_PATH"
|
||||
|
||||
# Save original default keychain for cleanup
|
||||
ORIGINAL_DEFAULT_KEYCHAIN=$(security default-keychain -d user | tr -d '"' | xargs)
|
||||
echo "ORIGINAL_DEFAULT_KEYCHAIN=$ORIGINAL_DEFAULT_KEYCHAIN" >> "$GITHUB_ENV"
|
||||
|
||||
# Create temporary keychain
|
||||
KEYCHAIN_PATH="$RUNNER_TEMP/build.keychain-db"
|
||||
security create-keychain -p "${{ secrets.KEYCHAIN_PASSWORD }}" "$KEYCHAIN_PATH"
|
||||
security set-keychain-settings -lut 21600 "$KEYCHAIN_PATH"
|
||||
security default-keychain -s "$KEYCHAIN_PATH"
|
||||
security unlock-keychain -p "${{ secrets.KEYCHAIN_PASSWORD }}" "$KEYCHAIN_PATH"
|
||||
|
||||
# Import certificate
|
||||
security import "$CERT_PATH" \
|
||||
-k "$KEYCHAIN_PATH" \
|
||||
-P "${{ secrets.APPLE_CERTIFICATE_PASSWORD }}" \
|
||||
-T /usr/bin/codesign \
|
||||
-T /usr/bin/security
|
||||
security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "${{ secrets.KEYCHAIN_PASSWORD }}" "$KEYCHAIN_PATH"
|
||||
|
||||
# Dynamically resolve signing identity (must be "Developer ID Application")
|
||||
IDENTITY=$(security find-identity -v -p codesigning "$KEYCHAIN_PATH" \
|
||||
| grep "Developer ID Application" | grep -oE '"[^"]+"' | head -1 | tr -d '"')
|
||||
if [ -z "$IDENTITY" ]; then
|
||||
echo "❌ No 'Developer ID Application' identity found — listing all identities:" >&2
|
||||
security find-identity -v -p codesigning "$KEYCHAIN_PATH"
|
||||
exit 1
|
||||
fi
|
||||
echo "✅ Signing identity: $IDENTITY"
|
||||
echo "APPLE_SIGNING_IDENTITY=$IDENTITY" >> "$GITHUB_ENV"
|
||||
|
||||
# Cleanup certificate file
|
||||
rm -f "$CERT_PATH"
|
||||
|
||||
- name: Build Tauri App (macOS)
|
||||
if: runner.os == 'macOS'
|
||||
run: pnpm tauri build --target universal-apple-darwin
|
||||
shell: bash
|
||||
timeout-minutes: 60
|
||||
env:
|
||||
APPLE_SIGNING_IDENTITY: ${{ env.APPLE_SIGNING_IDENTITY }}
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
max_attempts=3
|
||||
for attempt in $(seq 1 "$max_attempts"); do
|
||||
echo "=== macOS build/notarization attempt ${attempt}/${max_attempts} ==="
|
||||
if pnpm tauri build --target universal-apple-darwin; then
|
||||
echo "✅ macOS build/notarization succeeded"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ "$attempt" -eq "$max_attempts" ]; then
|
||||
echo "❌ macOS build/notarization failed after ${max_attempts} attempts" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
sleep_seconds=$((attempt * 60))
|
||||
echo "⚠️ macOS build/notarization failed, retrying in ${sleep_seconds}s..."
|
||||
sleep "$sleep_seconds"
|
||||
done
|
||||
|
||||
- name: Build Tauri App (Windows)
|
||||
if: runner.os == 'Windows'
|
||||
@@ -169,7 +236,8 @@ jobs:
|
||||
set -euxo pipefail
|
||||
mkdir -p release-assets
|
||||
VERSION="${GITHUB_REF_NAME}" # e.g., v3.5.0
|
||||
echo "Looking for updater artifact (.tar.gz) and .app for zip..."
|
||||
|
||||
# Locate bundle artifacts
|
||||
TAR_GZ=""; APP_PATH=""
|
||||
for path in \
|
||||
"src-tauri/target/universal-apple-darwin/release/bundle/macos" \
|
||||
@@ -177,28 +245,150 @@ jobs:
|
||||
"src-tauri/target/x86_64-apple-darwin/release/bundle/macos" \
|
||||
"src-tauri/target/release/bundle/macos"; do
|
||||
if [ -d "$path" ]; then
|
||||
[ -z "$TAR_GZ" ] && TAR_GZ=$(find "$path" -maxdepth 1 -name "*.tar.gz" -type f | head -1 || true)
|
||||
[ -z "$TAR_GZ" ] && TAR_GZ=$(find "$path" -maxdepth 1 -name "*.tar.gz" -type f | head -1 || true)
|
||||
[ -z "$APP_PATH" ] && APP_PATH=$(find "$path" -maxdepth 1 -name "*.app" -type d | head -1 || true)
|
||||
fi
|
||||
done
|
||||
|
||||
if [ -z "$TAR_GZ" ]; then
|
||||
echo "No macOS .tar.gz updater artifact found" >&2
|
||||
echo "❌ No macOS .tar.gz updater artifact found" >&2
|
||||
exit 1
|
||||
fi
|
||||
# 重命名 tar.gz 为统一格式
|
||||
if [ -z "$APP_PATH" ]; then
|
||||
echo "❌ No .app found" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Staple notarization ticket to .app (Tauri already notarized it)
|
||||
xcrun stapler staple "$APP_PATH"
|
||||
echo "✅ .app stapled"
|
||||
|
||||
# 1) Collect .tar.gz (updater artifact)
|
||||
NEW_TAR_GZ="CC-Switch-${VERSION}-macOS.tar.gz"
|
||||
cp "$TAR_GZ" "release-assets/$NEW_TAR_GZ"
|
||||
[ -f "$TAR_GZ.sig" ] && cp "$TAR_GZ.sig" "release-assets/$NEW_TAR_GZ.sig" || echo ".sig for macOS not found yet"
|
||||
echo "macOS updater artifact copied: $NEW_TAR_GZ"
|
||||
if [ -n "$APP_PATH" ]; then
|
||||
APP_DIR=$(dirname "$APP_PATH"); APP_NAME=$(basename "$APP_PATH")
|
||||
NEW_ZIP="CC-Switch-${VERSION}-macOS.zip"
|
||||
cd "$APP_DIR"
|
||||
ditto -c -k --sequesterRsrc --keepParent "$APP_NAME" "$NEW_ZIP"
|
||||
mv "$NEW_ZIP" "$GITHUB_WORKSPACE/release-assets/"
|
||||
echo "macOS zip ready: $NEW_ZIP"
|
||||
|
||||
# 2) Collect .app as zip
|
||||
NEW_ZIP="CC-Switch-${VERSION}-macOS.zip"
|
||||
ditto -c -k --sequesterRsrc --keepParent "$APP_PATH" "release-assets/$NEW_ZIP"
|
||||
echo "macOS zip ready: $NEW_ZIP"
|
||||
|
||||
# 3) Create styled DMG with create-dmg (Tauri's built-in DMG styling doesn't work on CI)
|
||||
if [ -z "${APPLE_SIGNING_IDENTITY:-}" ]; then
|
||||
echo "❌ APPLE_SIGNING_IDENTITY is missing before DMG creation" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
HOMEBREW_NO_AUTO_UPDATE=1 brew install create-dmg
|
||||
NEW_DMG="CC-Switch-${VERSION}-macOS.dmg"
|
||||
DMG_STAGE_DIR="$RUNNER_TEMP/dmg-stage"
|
||||
rm -rf "$DMG_STAGE_DIR"
|
||||
mkdir -p "$DMG_STAGE_DIR"
|
||||
ditto "$APP_PATH" "$DMG_STAGE_DIR/CC Switch.app"
|
||||
|
||||
create-dmg \
|
||||
--volname "CC Switch" \
|
||||
--background "src-tauri/icons/dmg-background.png" \
|
||||
--window-size 660 400 \
|
||||
--window-pos 200 120 \
|
||||
--icon-size 80 \
|
||||
--icon "CC Switch.app" 180 220 \
|
||||
--hide-extension "CC Switch.app" \
|
||||
--app-drop-link 480 220 \
|
||||
--codesign "$APPLE_SIGNING_IDENTITY" \
|
||||
--no-internet-enable \
|
||||
"release-assets/$NEW_DMG" \
|
||||
"$DMG_STAGE_DIR"
|
||||
|
||||
rm -rf "$DMG_STAGE_DIR"
|
||||
echo "✅ Styled DMG created: $NEW_DMG"
|
||||
|
||||
- name: Notarize macOS DMG
|
||||
if: runner.os == 'macOS'
|
||||
shell: bash
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
DMG_PATH=$(find release-assets -maxdepth 1 -name "*.dmg" -type f | head -1 || true)
|
||||
if [ -z "$DMG_PATH" ]; then
|
||||
echo "❌ No .dmg found in release-assets/ to notarize" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "=== Notarizing DMG: $DMG_PATH ==="
|
||||
max_attempts=3
|
||||
for attempt in $(seq 1 "$max_attempts"); do
|
||||
echo "=== DMG notarization attempt ${attempt}/${max_attempts} ==="
|
||||
if xcrun notarytool submit "$DMG_PATH" \
|
||||
--apple-id "$APPLE_ID" \
|
||||
--password "$APPLE_PASSWORD" \
|
||||
--team-id "$APPLE_TEAM_ID" \
|
||||
--wait; then
|
||||
echo "✅ DMG notarization succeeded"
|
||||
xcrun stapler staple "$DMG_PATH"
|
||||
echo "✅ DMG stapled"
|
||||
break
|
||||
fi
|
||||
|
||||
if [ "$attempt" -eq "$max_attempts" ]; then
|
||||
echo "❌ DMG notarization failed after ${max_attempts} attempts" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
sleep_seconds=$((attempt * 60))
|
||||
echo "⚠️ DMG notarization failed, retrying in ${sleep_seconds}s..."
|
||||
sleep "$sleep_seconds"
|
||||
done
|
||||
|
||||
- name: Verify macOS code signing and notarization
|
||||
if: runner.os == 'macOS'
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
# Verify .app (from Tauri bundle)
|
||||
APP_PATH=""
|
||||
for path in \
|
||||
"src-tauri/target/universal-apple-darwin/release/bundle/macos" \
|
||||
"src-tauri/target/aarch64-apple-darwin/release/bundle/macos" \
|
||||
"src-tauri/target/x86_64-apple-darwin/release/bundle/macos" \
|
||||
"src-tauri/target/release/bundle/macos"; do
|
||||
if [ -d "$path" ]; then
|
||||
[ -z "$APP_PATH" ] && APP_PATH=$(find "$path" -maxdepth 1 -name "*.app" -type d | head -1 || true)
|
||||
fi
|
||||
done
|
||||
|
||||
if [ -z "$APP_PATH" ]; then
|
||||
echo "❌ No .app found for verification" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "=== Verifying .app: $APP_PATH ==="
|
||||
codesign --verify --deep --strict --verbose=2 "$APP_PATH"
|
||||
echo "✅ codesign verification passed"
|
||||
spctl -a -t exec -vv "$APP_PATH"
|
||||
echo "✅ spctl assessment passed"
|
||||
xcrun stapler validate "$APP_PATH"
|
||||
echo "✅ .app stapler validation passed"
|
||||
|
||||
# Verify .dmg (from release-assets/, created by create-dmg + notarized)
|
||||
DMG_PATH=$(find release-assets -maxdepth 1 -name "*.dmg" -type f | head -1 || true)
|
||||
if [ -n "$DMG_PATH" ]; then
|
||||
echo "=== Verifying .dmg: $DMG_PATH ==="
|
||||
codesign --verify --verbose=2 "$DMG_PATH"
|
||||
echo "✅ .dmg codesign verification passed"
|
||||
spctl -a -t open --context context:primary-signature -vv "$DMG_PATH"
|
||||
echo "✅ .dmg spctl assessment passed"
|
||||
xcrun stapler validate "$DMG_PATH"
|
||||
echo "✅ .dmg stapler validation passed"
|
||||
else
|
||||
echo "No .app found to zip (optional)" >&2
|
||||
echo "❌ No .dmg found for verification — release would ship without verified DMG" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Prepare Windows Assets
|
||||
@@ -299,6 +489,51 @@ jobs:
|
||||
echo "Collected signatures (if any alongside artifacts):"
|
||||
ls -la release-assets/*.sig || echo "No signatures found"
|
||||
|
||||
- name: Upload release artifacts to workflow
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: release-assets-${{ runner.os }}-${{ matrix.arch || runner.arch }}
|
||||
path: release-assets/*
|
||||
if-no-files-found: error
|
||||
|
||||
- name: List generated bundles (debug)
|
||||
if: always()
|
||||
shell: bash
|
||||
run: |
|
||||
echo "Listing bundles in src-tauri/target..."
|
||||
find src-tauri/target -maxdepth 4 -type f -name "*.*" 2>/dev/null || true
|
||||
|
||||
- name: Clean up Apple signing keychain
|
||||
if: runner.os == 'macOS' && always()
|
||||
shell: bash
|
||||
run: |
|
||||
if [ -n "${ORIGINAL_DEFAULT_KEYCHAIN:-}" ]; then
|
||||
security default-keychain -s "$ORIGINAL_DEFAULT_KEYCHAIN" || true
|
||||
fi
|
||||
if [ -f "$RUNNER_TEMP/build.keychain-db" ]; then
|
||||
security delete-keychain "$RUNNER_TEMP/build.keychain-db" || true
|
||||
fi
|
||||
|
||||
publish-release:
|
||||
name: Publish GitHub Release
|
||||
runs-on: ubuntu-22.04
|
||||
needs: release
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- name: Download built release artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
pattern: release-assets-*
|
||||
path: release-assets
|
||||
merge-multiple: true
|
||||
|
||||
- name: List downloaded release artifacts
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
ls -la release-assets
|
||||
|
||||
- name: Upload Release Assets
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
@@ -312,28 +547,23 @@ jobs:
|
||||
|
||||
### 下载
|
||||
|
||||
- **macOS**: `CC-Switch-${{ github.ref_name }}-macOS.zip`(解压即用)或 `CC-Switch-${{ github.ref_name }}-macOS.tar.gz`(Homebrew)
|
||||
- **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`(绿色版)
|
||||
- **Linux (x86_64)**: `CC-Switch-${{ github.ref_name }}-Linux-x86_64.AppImage` / `.deb` / `.rpm`
|
||||
- **Linux (ARM64)**: `CC-Switch-${{ github.ref_name }}-Linux-arm64.AppImage` / `.deb` / `.rpm`
|
||||
|
||||
> `.tar.gz` 为 Tauri updater 自动更新专用,无需手动下载。
|
||||
|
||||
---
|
||||
提示:macOS 如遇"已损坏"提示,可在终端执行:`xattr -cr "/Applications/CC Switch.app"`
|
||||
macOS 版本已通过 Apple 代码签名和公证,可直接安装使用。
|
||||
files: release-assets/*
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: List generated bundles (debug)
|
||||
if: always()
|
||||
shell: bash
|
||||
run: |
|
||||
echo "Listing bundles in src-tauri/target..."
|
||||
find src-tauri/target -maxdepth 4 -type f -name "*.*" 2>/dev/null || true
|
||||
|
||||
assemble-latest-json:
|
||||
name: Assemble latest.json
|
||||
runs-on: ubuntu-22.04
|
||||
needs: release
|
||||
needs: publish-release
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
|
||||
+5
-1
@@ -24,4 +24,8 @@ flatpak/cc-switch.deb
|
||||
flatpak-build/
|
||||
flatpak-repo/
|
||||
.worktrees/
|
||||
.spec-workflow/
|
||||
.spec-workflow/
|
||||
copilot-api
|
||||
.history
|
||||
CODEBUDDY.md
|
||||
.github
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
22.12.0
|
||||
22.12.0
|
||||
|
||||
@@ -9,6 +9,86 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
---
|
||||
|
||||
## [3.12.3] - 2026-03-24
|
||||
|
||||
Major release adding GitHub Copilot reverse proxy support, macOS code signing & Apple notarization, intelligent reasoning effort mapping for o-series models, skill backup/restore lifecycle, proxy gzip compression, and critical fixes for WebDAV password safety, tool message parsing, and dark mode.
|
||||
|
||||
**Stats**: 36 commits | 107 files changed | +9,124 insertions | -802 deletions
|
||||
|
||||
### Added
|
||||
|
||||
- **GitHub Copilot Reverse Proxy**: Full GitHub Copilot integration as a Claude Code provider via OAuth Device Code flow; includes multi-account management, automatic token refresh, Anthropic ↔ OpenAI format conversion, real-time model list fetching, and usage statistics (#930)
|
||||
- **Copilot Auth Center**: New Auth Center panel in Settings for managing GitHub accounts globally, with per-provider account binding via `meta.authBinding`
|
||||
- **Tool Search Toggle**: Added `ENABLE_TOOL_SEARCH` env var support for Claude 2.1.76+; exposed as a checkbox in the provider Common Config editor (#930)
|
||||
- **Reasoning Effort Mapping**: Two-tier `resolve_reasoning_effort()` for OpenAI o-series and GPT-5+ models — explicit `output_config.effort` takes priority, falling back to thinking `budget_tokens` thresholds (<4 000→low, 4 000–16 000→medium, ≥16 000→high); covers both Chat Completions and Responses API paths with 17 unit tests
|
||||
- **OpenCode SQLite Backend**: Added SQLite session storage support for OpenCode alongside existing JSON backend; dual-backend scan with SQLite priority on ID conflicts, atomic session deletion, and path validation (#1401)
|
||||
- **Skill Auto-Backup**: Skill files are automatically backed up to `~/.cc-switch/skill-backups/` before uninstall, with metadata preserved in `meta.json`; old backups pruned to keep at most 20
|
||||
- **Skill Backup Restore & Delete**: Added list/restore/delete commands for skill backups; restore copies files back to SSOT, saves the DB record, and syncs to the current app with rollback on failure
|
||||
- **macOS Code Signing & Notarization**: CI now imports an Apple Developer ID certificate, signs the universal binary, submits for Apple notarization, and staples the ticket to both `.app` and `.dmg`; a hard-fail verification step (`codesign --verify` + `spctl -a` + `stapler validate`) gates the release for both artifacts
|
||||
- **Codex 1M Context Window Toggle**: One-click checkbox in Codex config editor to set `model_context_window = 1000000` with auto-populated `model_auto_compact_token_limit = 900000`; unchecking removes both fields
|
||||
- **Disable Auto-Upgrade Toggle**: Added `DISABLE_AUTOUPDATER` env var checkbox in the Claude Common Config editor to prevent Claude Code from auto-upgrading
|
||||
|
||||
### Changed
|
||||
|
||||
- **Skills Cache Strategy**: Replaced `invalidateQueries` with direct `setQueryData` updates for skill install/uninstall/import operations; added `staleTime: Infinity` with `keepPreviousData` to eliminate loading flicker (#1573)
|
||||
- **Proxy Gzip Compression**: Non-streaming proxy requests now auto-negotiate gzip compression instead of forcing `identity`; streaming requests conservatively keep `identity` to avoid SSE decompression errors
|
||||
- **o1/o3 Model Compatibility**: Chat Completions proxy forwarding now correctly uses `max_completion_tokens` instead of `max_tokens` for OpenAI o-series models such as o1/o3/o4-mini (#1451)
|
||||
- **OpenCode Model Variants**: Placed OpenCode model variants at top level instead of inside options for better discoverability (#1317)
|
||||
- **Skills Import Flow**: Replaced implicit filesystem-based app inference with explicit `ImportSkillSelection` to prevent incorrect multi-app activation; added reconciliation to remove disabled/orphaned symlinks and MCP servers from live config
|
||||
- **Claude 4.6 Context Window**: Updated Claude Opus 4.6 and Sonnet 4.6 context window from 200K to 1M across OpenClaw and OpenCode presets (GA release)
|
||||
- **MiniMax Model Upgrade**: Updated MiniMax presets from M2.5 to M2.7 across Claude, OpenClaw, and OpenCode configurations with updated partner descriptions in all three locales
|
||||
- **Xiaomi MiMo Model Upgrade**: Updated MiMo presets from mimo-v2-flash to mimo-v2-pro across all supported applications
|
||||
- **AddProviderDialog Simplification**: Removed redundant OAuth tab, reducing dialog from 3 tabs to 2 (app-specific + universal)
|
||||
- **Provider Form Advanced Options Collapse**: Model mapping, API format, and other advanced fields in the Claude provider form now auto-collapse when empty; auto-expands when any value is set or when a preset fills them in
|
||||
|
||||
### Fixed
|
||||
|
||||
- **WebDAV Password Silent Clear**: Fixed WebDAV password being silently wiped when ProviderList or UsageScriptModal saved settings by stripping `webdavSync` from frontend payloads and adding backend backfill logic in `merge_settings_for_save()` to preserve existing passwords
|
||||
- **Tool Message Parsing**: Fixed tool_use/tool_result message classification across Claude (tool_result content blocks), Codex (function_call/function_call_output payloads), and Gemini (array content + toolCalls extraction) session providers (#1401)
|
||||
- **Dark Mode Selector**: Changed Tailwind `darkMode` from `["selector", "class"]` to `["selector", ".dark"]` to ensure correct dark mode activation (#1596)
|
||||
- **Copilot Request Fingerprint**: Unified Copilot request fingerprint headers across all API call sites to prevent User-Agent leakage and stream check mismatches
|
||||
- **o-series Responses API Tokens**: Kept Responses API on the correct `max_output_tokens` field for o-series models instead of incorrectly injecting `max_completion_tokens`
|
||||
- **Provider Form Double Submit**: Prevented duplicate submissions on rapid button clicks in provider add/edit forms (#1352)
|
||||
- **Ghostty Session Restore**: Fixed Claude session restore in Ghostty terminal (#1506)
|
||||
- **Skill ZIP Import Extension**: Added `.skill` file extension support in ZIP import dialog (#1240, #1455)
|
||||
- **Skill ZIP Install Target App**: ZIP skill installs now use the currently active app instead of always defaulting to Claude
|
||||
- **OpenClaw Active Card Highlight**: Fixed active OpenClaw provider card not being highlighted (#1419)
|
||||
- **Responsive Layout with TOC**: Improved responsive design when TOC title exists (#1491)
|
||||
- **Import Skills Dialog White Screen**: Added missing TooltipProvider in ImportSkillsDialog to prevent runtime crash when opening the dialog
|
||||
- **Panel Bottom Blank Area**: Replaced hardcoded `h-[calc(100vh-8rem)]` with `flex-1 min-h-0` across all content panels to eliminate bottom gap caused by mismatched offset values
|
||||
|
||||
### Docs
|
||||
|
||||
- **Pricing Model ID Normalization**: Added documentation section explaining model ID normalization rules (prefix stripping, suffix trimming, `@`→`-` replacement) in EN/ZH/JA user manuals (#1591)
|
||||
- **macOS Signed & Notarized**: Removed all `xattr` workaround instructions and "unidentified developer" warnings from README, README_ZH, installation guides (EN/ZH/JA), and FAQ pages (EN/ZH/JA); replaced with "signed and notarized by Apple" messaging
|
||||
|
||||
---
|
||||
|
||||
## [3.12.2] - 2026-03-12
|
||||
|
||||
Post-v3.12.1 work focuses on Common Config safety during proxy takeover and more reliable Codex TOML editing.
|
||||
|
||||
**Stats**: 5 commits | 22 files changed | +1,716 insertions | -288 deletions
|
||||
|
||||
### Added
|
||||
|
||||
- **Empty State Guidance**: Improved first-run experience with detailed import instructions and a conditional Common Config snippet hint for Claude/Codex/Gemini providers
|
||||
|
||||
### Changed
|
||||
|
||||
- **Proxy Takeover Restore Flow**: Proxy takeover hot-switch and provider sync now refresh the restore backup instead of overwriting live config files, rebuilding effective provider settings with Common Config applied so rollback preserves the real user configuration
|
||||
- **Codex TOML Editing Engine**: Refactored Codex `config.toml` updates onto shared section-aware TOML helpers in Rust and TypeScript, covering `base_url` and `model` field edits across provider forms and takeover cleanup
|
||||
- **Common Config Initialization Lifecycle**: Startup now auto-extracts Common Config snippets from clean live configs before takeover restoration, tracks explicit "snippet cleared" state, and persists a one-time legacy migration flag to avoid repeated backfills
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Common Config Loss During Takeover**: Fixed cases where proxy takeover could drop Common Config changes, overwrite live configs during sync, or produce incomplete restore snapshots when switching providers
|
||||
- **Codex Restore Snapshot Preservation**: Fixed Codex takeover restore backups so existing `mcp_servers` blocks survive provider hot-switches instead of being discarded; changed MCP backup preservation from wholesale table replacement to per-server-id merge so provider/common-config MCP updates win on conflict while live-only servers are retained
|
||||
- **Cleared Snippet Resurrection**: Fixed startup auto-extraction recreating Common Config snippets that users had intentionally cleared
|
||||
- **Codex `base_url` Misplacement**: Fixed Codex `base_url` extraction and editing to target the active `[model_providers.<name>]` section instead of appending to the file tail or confusing `mcp_servers.*.base_url` entries for provider endpoints
|
||||
|
||||
---
|
||||
|
||||
## [3.12.1] - 2026-03-12
|
||||
|
||||
### Patch Release
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
### The All-in-One Manager for Claude Code, Codex, Gemini CLI, OpenCode & OpenClaw
|
||||
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://tauri.app/)
|
||||
[](https://github.com/farion1231/cc-switch/releases/latest)
|
||||
@@ -22,9 +22,9 @@ English | [中文](README_ZH.md) | [日本語](README_JA.md) | [Changelog](CHANG
|
||||
|
||||
[](https://platform.minimax.io/subscribe/coding-plan?code=ClLhgxr2je&source=link)
|
||||
|
||||
MiniMax-M2.5 is a SOTA large language model designed for real-world productivity. Trained in a diverse range of complex real-world digital working environments, M2.5 builds upon the coding expertise of M2.1 to extend into general office work, reaching fluency in generating and operating Word, Excel, and Powerpoint files, context switching between diverse software environments, and working across different agent and human teams. Scoring 80.2% on SWE-Bench Verified, 51.3% on Multi-SWE-Bench, and 76.3% on BrowseComp, M2.5 is also more token efficient than previous generations, having been trained to optimize its actions and output through planning.
|
||||
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 Coding Plan!
|
||||
[Click](https://platform.minimax.io/subscribe/coding-plan?code=ClLhgxr2je&source=link) to get an exclusive 12% off the MiniMax Token Plan!
|
||||
|
||||
---
|
||||
|
||||
@@ -100,6 +100,11 @@ Claude Code / Codex / Gemini official channels at 38% / 2% / 9% of original pric
|
||||
<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>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://chefshop.ai"><img src="assets/partners/logos/chefshop.png" alt="ChefShop" width="150"></a></td>
|
||||
<td>Thanks to ChefShop AI for sponsoring this project! ChefShop AI is a premium account service provider tailored for heavy AI subscription users. The platform offers official top-up and stable account services for mainstream large models including ChatGPT Plus/Pro, Claude Max, Grok Super/Heavy, and Gemini. Click <a href="https://chefshop.ai">here</a> to purchase!</td>
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
|
||||
</details>
|
||||
@@ -126,7 +131,7 @@ Modern AI-powered coding relies on CLI tools like Claude Code, Codex, Gemini CLI
|
||||
|
||||
## Features
|
||||
|
||||
[Full Changelog](CHANGELOG.md) | [Release Notes](docs/release-notes/v3.12.1-en.md)
|
||||
[Full Changelog](CHANGELOG.md) | [Release Notes](docs/release-notes/v3.12.3-en.md)
|
||||
|
||||
### Provider Management
|
||||
|
||||
@@ -184,9 +189,9 @@ CC Switch provides a "Shared Config Snippet" feature to pass common data (beyond
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>macOS shows "unidentified developer" warning — how do I fix it?</strong></summary>
|
||||
<summary><strong>macOS installation</strong></summary>
|
||||
|
||||
The author doesn't have an Apple Developer account yet (registration in progress). Close the warning, then go to **System Settings → Privacy & Security → Open Anyway**. After that, the app will open normally.
|
||||
CC Switch for macOS is code-signed and notarized by Apple. You can download and install it directly — no extra steps needed. We recommend using the `.dmg` installer.
|
||||
|
||||
</details>
|
||||
|
||||
@@ -211,6 +216,7 @@ Add an official provider from the preset list. After switching to it, run the Lo
|
||||
- **Local settings**: `~/.cc-switch/settings.json` (device-level UI preferences)
|
||||
- **Backups**: `~/.cc-switch/backups/` (auto-rotated, keeps 10 most recent)
|
||||
- **Skills**: `~/.cc-switch/skills/` (symlinked to corresponding apps by default)
|
||||
- **Skill Backups**: `~/.cc-switch/skill-backups/` (created automatically before uninstall, keeps 20 most recent)
|
||||
|
||||
</details>
|
||||
|
||||
@@ -243,7 +249,7 @@ For detailed guides on every feature, check out the **[User Manual](docs/user-ma
|
||||
### System Requirements
|
||||
|
||||
- **Windows**: Windows 10 and above
|
||||
- **macOS**: macOS 10.15 (Catalina) and above
|
||||
- **macOS**: macOS 12 (Monterey) and above
|
||||
- **Linux**: Ubuntu 22.04+ / Debian 11+ / Fedora 34+ and other mainstream distributions
|
||||
|
||||
### Windows Users
|
||||
@@ -267,9 +273,9 @@ brew upgrade --cask cc-switch
|
||||
|
||||
**Method 2: Manual Download**
|
||||
|
||||
Download `CC-Switch-v{version}-macOS.zip` from the [Releases](../../releases) page and extract to use.
|
||||
Download `CC-Switch-v{version}-macOS.dmg` (recommended) or `.zip` from the [Releases](../../releases) page.
|
||||
|
||||
> **Note**: Since the author doesn't have an Apple Developer account, you may see an "unidentified developer" warning on first launch. Please close it first, then go to "System Settings" → "Privacy & Security" → click "Open Anyway", and you'll be able to open it normally afterwards.
|
||||
> **Note**: CC Switch for macOS is code-signed and notarized by Apple. You can install and open it directly.
|
||||
|
||||
### Arch Linux Users
|
||||
|
||||
|
||||
+11
-5
@@ -4,7 +4,7 @@
|
||||
|
||||
### Claude Code、Codex、Gemini CLI、OpenCode、OpenClaw のオールインワン管理ツール
|
||||
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://tauri.app/)
|
||||
[](https://github.com/farion1231/cc-switch/releases/latest)
|
||||
@@ -22,9 +22,9 @@
|
||||
|
||||
[](https://platform.minimax.io/subscribe/coding-plan?code=ClLhgxr2je&source=link)
|
||||
|
||||
MiniMax-M2.5 は、実際の生産性向上のために設計された最先端の大規模言語モデルです。多様で複雑な実環境のデジタルワークスペースでトレーニングされた M2.5 は、M2.1 のコーディング能力をベースに一般的なオフィス業務へと拡張し、Word・Excel・PowerPoint ファイルの生成と操作、多様なソフトウェア環境間のコンテキスト切り替え、異なるエージェントや人間チーム間での協働を流暢にこなします。SWE-Bench Verified で 80.2%、Multi-SWE-Bench で 51.3%、BrowseComp で 76.3% を達成し、計画的な行動と出力の最適化トレーニングにより、前世代よりもトークン効率に優れています。
|
||||
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 Coding Plan の限定 12% オフを入手!
|
||||
[こちら](https://platform.minimax.io/subscribe/coding-plan?code=ClLhgxr2je&source=link)から MiniMax Token Plan の限定 12% オフを入手!
|
||||
|
||||
---
|
||||
|
||||
@@ -100,6 +100,11 @@ Claude Code / Codex / Gemini 公式チャンネルが最安で元価格の 38% /
|
||||
<td>CTok.ai のご支援に感謝します!CTok.ai はワンストップ AI プログラミングツールサービスプラットフォームの構築に取り組んでいます。Claude Code のプロフェッショナルプランと技術コミュニティサービスを提供し、Google Gemini や OpenAI Codex にも対応しています。丁寧に設計されたプランと専門的な技術コミュニティを通じて、開発者に安定したサービス保証と継続的な技術サポートを提供し、AI アシストプログラミングを真の生産性ツールにします。<a href="https://ctok.ai">こちら</a>から登録してください!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://chefshop.ai"><img src="assets/partners/logos/chefshop.png" alt="ChefShop" width="150"></a></td>
|
||||
<td>ChefShop AI のご支援に感謝します!ChefShop AI は、AI ヘビーユーザー向けにカスタマイズされたプレミアムアカウントサービスプロバイダーです。ChatGPT Plus/Pro、Claude Max、Grok Super/Heavy、Gemini など主流の大規模モデルの公式チャージと安定したアカウントサービスを提供しています。<a href="https://chefshop.ai">こちら</a>から購入してください!</td>
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
|
||||
</details>
|
||||
@@ -126,7 +131,7 @@ Claude Code / Codex / Gemini 公式チャンネルが最安で元価格の 38% /
|
||||
|
||||
## 特長
|
||||
|
||||
[完全な更新履歴](CHANGELOG.md) | [リリースノート](docs/release-notes/v3.12.1-ja.md)
|
||||
[完全な更新履歴](CHANGELOG.md) | [リリースノート](docs/release-notes/v3.12.3-ja.md)
|
||||
|
||||
### プロバイダ管理
|
||||
|
||||
@@ -211,6 +216,7 @@ CC Switch は「最小限の介入」という設計原則に従っています
|
||||
- **ローカル設定**: `~/.cc-switch/settings.json`(デバイスレベルの UI 設定)
|
||||
- **バックアップ**: `~/.cc-switch/backups/`(自動ローテーション、最新 10 件を保持)
|
||||
- **Skills**: `~/.cc-switch/skills/`(デフォルトでシンボリックリンクにより対応アプリに接続)
|
||||
- **Skill バックアップ**: `~/.cc-switch/skill-backups/`(アンインストール前に自動作成、最新 20 件を保持)
|
||||
|
||||
</details>
|
||||
|
||||
@@ -243,7 +249,7 @@ CC Switch は「最小限の介入」という設計原則に従っています
|
||||
### システム要件
|
||||
|
||||
- **Windows**: Windows 10 以上
|
||||
- **macOS**: macOS 10.15 (Catalina) 以上
|
||||
- **macOS**: macOS 12 (Monterey) 以上
|
||||
- **Linux**: Ubuntu 22.04+ / Debian 11+ / Fedora 34+ など主要ディストリビューション
|
||||
|
||||
### Windows ユーザー
|
||||
|
||||
+15
-9
@@ -4,7 +4,7 @@
|
||||
|
||||
### Claude Code、Codex、Gemini CLI、OpenCode 和 OpenClaw 的全方位管理工具
|
||||
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://tauri.app/)
|
||||
[](https://github.com/farion1231/cc-switch/releases/latest)
|
||||
@@ -22,9 +22,9 @@
|
||||
|
||||
[](https://platform.minimaxi.com/subscribe/coding-plan?code=7kYF2VoaCn&source=link)
|
||||
|
||||
MiniMax M2.5 在编程、工具调用与搜索、办公等核心生产力场景均达到或刷新行业 SOTA,拥有架构师级代码能力与高效任务拆解能力,推理速度较上一代提升 37%、token 消耗更优;100 token/s 连续工作一小时仅需 1 美金,让复杂 Agent 规模化部署经济可行,已在企业多职能场景深度落地,加速全民 Agent 时代到来。
|
||||
MiniMax M2.7 是 MiniMax 首个深度参与自我迭代的模型,可自主构建复杂 Agent Harness,并基于 Agent Teams、复杂 Skills、Tool Search Tool 等能力完成高复杂度生产力任务;其在软件工程、端到端项目交付及办公场景中表现优异,多项评测接近行业领先水平,同时具备稳定的复杂任务执行、环境交互能力以及良好的情商与身份保持能力。
|
||||
|
||||
[点击](https://platform.minimaxi.com/subscribe/coding-plan?code=7kYF2VoaCn&source=link)即可领取 MiniMax Coding Plan 专属 88 折优惠!
|
||||
[点击此处](https://platform.minimaxi.com/subscribe/coding-plan?code=7kYF2VoaCn&source=link)享 MiniMax Token Plan 专属 88 折优惠!
|
||||
|
||||
---
|
||||
|
||||
@@ -101,6 +101,11 @@ Claude Code / Codex / Gemini 官方渠道低至 3.8 / 0.2 / 0.9 折,充值更
|
||||
<td>感谢 CTok.ai 赞助了本项目!CTok.ai 致力于打造一站式 AI 编程工具服务平台。我们提供 Claude Code 专业套餐及技术社群服务,同时支持 Google Gemini 和 OpenAI Codex。通过精心设计的套餐方案和专业的技术社群,为开发者提供稳定的服务保障和持续的技术支持,让 AI 辅助编程真正成为开发者的生产力工具。点击<a href="https://ctok.ai">这里</a>注册!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://chefshop.ai"><img src="assets/partners/logos/chefshop.png" alt="ChefShop" width="150"></a></td>
|
||||
<td>感谢 厨师长AI小铺 赞助了本项目!厨师长AI小铺 是一家专为 AI 重度订阅用户量身定制的优质账号服务商。平台提供涵盖 ChatGPT Plus/Pro、Claude Max、Grok Super/Heavy 以及 Gemini 等主流大模型的官方代充与稳定成品账号服务。点击<a href="https://chefshop.ai">这里</a>购买!</td>
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
|
||||
</details>
|
||||
@@ -127,7 +132,7 @@ Claude Code / Codex / Gemini 官方渠道低至 3.8 / 0.2 / 0.9 折,充值更
|
||||
|
||||
## 功能特性
|
||||
|
||||
[完整更新日志](CHANGELOG.md) | [发布说明](docs/release-notes/v3.12.1-zh.md)
|
||||
[完整更新日志](CHANGELOG.md) | [发布说明](docs/release-notes/v3.12.3-zh.md)
|
||||
|
||||
### 供应商管理
|
||||
|
||||
@@ -185,9 +190,9 @@ CC Switch 使用“通用配置片段”功能,在不同的供应商之间传
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>macOS 提示"未知开发者"警告 — 如何解决?</strong></summary>
|
||||
<summary><strong>macOS 安装</strong></summary>
|
||||
|
||||
这是由于作者没有苹果开发者账号(正在注册中)。关闭警告后,前往**系统设置 → 隐私与安全性 → 仍要打开**。之后应用即可正常打开。
|
||||
CC Switch macOS 版本已通过 Apple 代码签名和公证,可直接下载安装,无需额外操作。推荐使用 `.dmg` 安装包。
|
||||
|
||||
</details>
|
||||
|
||||
@@ -214,6 +219,7 @@ CC Switch 使用“通用配置片段”功能,在不同的供应商之间传
|
||||
- **本地设置**:`~/.cc-switch/settings.json`(设备级 UI 偏好设置)
|
||||
- **备份**:`~/.cc-switch/backups/`(自动轮换,保留最近 10 个)
|
||||
- **SKILLS**:`~/.cc-switch/skills/`(默认通过软链接连接到对应应用)
|
||||
- **技能备份**:`~/.cc-switch/skill-backups/`(卸载前自动创建,保留最近 20 个)
|
||||
|
||||
</details>
|
||||
|
||||
@@ -246,7 +252,7 @@ CC Switch 使用“通用配置片段”功能,在不同的供应商之间传
|
||||
### 系统要求
|
||||
|
||||
- **Windows**:Windows 10 及以上
|
||||
- **macOS**:macOS 10.15 (Catalina) 及以上
|
||||
- **macOS**:macOS 12 (Monterey) 及以上
|
||||
- **Linux**:Ubuntu 22.04+ / Debian 11+ / Fedora 34+ 等主流发行版
|
||||
|
||||
### Windows 用户
|
||||
@@ -270,9 +276,9 @@ brew upgrade --cask cc-switch
|
||||
|
||||
**方式二:手动下载**
|
||||
|
||||
从 [Releases](../../releases) 页面下载 `CC-Switch-v{版本号}-macOS.zip` 解压使用。
|
||||
从 [Releases](../../releases) 页面下载 `CC-Switch-v{版本号}-macOS.dmg`(推荐)或 `.zip`。
|
||||
|
||||
> **注意**:由于作者没有苹果开发者账号,首次打开可能出现"未知开发者"警告,请先关闭,然后前往"系统设置" → "隐私与安全性" → 点击"仍要打开",之后便可以正常打开。
|
||||
> **注意**:CC Switch macOS 版本已通过 Apple 代码签名和公证,可直接安装打开。
|
||||
|
||||
### Arch Linux 用户
|
||||
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 207 KiB After Width: | Height: | Size: 902 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 193 KiB After Width: | Height: | Size: 895 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 280 KiB |
@@ -19,3 +19,4 @@
|
||||
"hooks": "@/hooks"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
# CC Switch v3.12.2
|
||||
|
||||
> Common Config Protection During Proxy Takeover, Snippet Lifecycle Stability, Section-Aware Codex TOML Editing
|
||||
|
||||
**[中文版 →](v3.12.2-zh.md) | [日本語版 →](v3.12.2-ja.md)**
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
CC Switch v3.12.2 is a reliability-focused patch release that addresses Common Config loss during proxy takeover and improves Codex TOML editing accuracy. Proxy takeover hot-switches and provider sync now update the restore backup instead of overwriting live config files; the startup sequence has been reordered so snippets are extracted from clean live files before takeover state is restored; and Codex `base_url` editing has been refactored into a section-aware model that no longer appends to the end of the file.
|
||||
|
||||
**Release Date**: 2026-03-12
|
||||
|
||||
**Update Scale**: 5 commits | 22 files changed | +1,716 / -288 lines
|
||||
|
||||
---
|
||||
|
||||
## Highlights
|
||||
|
||||
- **Empty state guidance**: Provider list empty state now shows detailed import instructions with a conditional Common Config snippet hint for Claude/Codex/Gemini
|
||||
|
||||
- **Proxy takeover restore flow rework**: Hot-switches and provider sync now refresh the restore backup instead of overwriting live config files, preserving the full user configuration on rollback
|
||||
- **Snippet lifecycle stability**: Introduced a `cleared` flag to prevent auto-extraction from resurrecting cleared snippets, and reordered startup to extract from clean state
|
||||
- **Section-aware Codex TOML editing**: `base_url` and `model` field reads/writes now target the correct `[model_providers.<name>]` section
|
||||
- **Codex MCP config protection**: Existing `mcp_servers` blocks in restore snapshots survive provider hot-switches via per-server-id merge instead of wholesale replacement, with provider/common-config definitions winning on conflict
|
||||
|
||||
---
|
||||
|
||||
## New Features
|
||||
|
||||
### Empty State Guidance
|
||||
|
||||
Improved the first-run experience with helpful guidance when the provider list is empty.
|
||||
|
||||
- Empty state page shows step-by-step import instructions
|
||||
- Conditionally displays a Common Config snippet hint for Claude/Codex/Gemini providers (not shown for OpenCode/OpenClaw)
|
||||
|
||||
---
|
||||
|
||||
## Changes
|
||||
|
||||
### Proxy Takeover Restore Flow
|
||||
|
||||
The proxy takeover hot-switch and provider sync logic has been reworked to protect Common Config throughout the takeover lifecycle.
|
||||
|
||||
- Provider sync now updates the restore backup instead of writing directly to live config files when takeover is active
|
||||
- Effective provider settings are rebuilt with Common Config applied before saving restore snapshots, so rollback restores the real user configuration
|
||||
- Legacy providers with inferred common config usage are automatically marked with `commonConfigEnabled=true`
|
||||
|
||||
### Codex TOML Editing Engine
|
||||
|
||||
Codex `config.toml` update logic has been refactored onto shared section-aware TOML helpers.
|
||||
|
||||
- New Rust module `codex_config.rs` with `update_codex_toml_field` and `remove_codex_toml_base_url_if`
|
||||
- New frontend utilities `getTomlSectionRange` / `getCodexProviderSectionName` for section-aware operations
|
||||
- Inline TOML editing logic scattered across `proxy.rs` now delegates to the new module
|
||||
|
||||
### Common Config Initialization Lifecycle
|
||||
|
||||
The startup sequence has been reordered for more robust snippet extraction and migration.
|
||||
|
||||
- Startup now auto-extracts Common Config snippets from clean live files before restoring proxy takeover state
|
||||
- Introduced a snippet `cleared` flag to track whether a user intentionally cleared a snippet
|
||||
- Persisted a one-time legacy migration flag to avoid repeated `commonConfigEnabled` backfills
|
||||
|
||||
---
|
||||
|
||||
## Bug Fixes
|
||||
|
||||
### Common Config Loss
|
||||
|
||||
- Fixed multiple scenarios where Common Config could be dropped during proxy takeover: sync overwriting live files, hot-switches producing incomplete restore snapshots, and provider switches losing config changes
|
||||
|
||||
### Codex Restore Snapshot Preservation
|
||||
|
||||
- Fixed Codex takeover restore backups discarding existing `mcp_servers` blocks during provider hot-switches; changed MCP backup preservation from wholesale table replacement to per-server-id merge so provider/common-config MCP updates win on conflict while backup-only servers are retained
|
||||
|
||||
### Cleared Snippet Resurrection
|
||||
|
||||
- Fixed startup auto-extraction recreating Common Config snippets that users had intentionally cleared
|
||||
|
||||
### Codex `base_url` Misplacement
|
||||
|
||||
- Fixed Codex `base_url` extraction and editing not targeting the correct `[model_providers.<name>]` section, causing it to append to the file tail or confuse `mcp_servers.*.base_url` entries for provider endpoints
|
||||
|
||||
---
|
||||
|
||||
## Download & Installation
|
||||
|
||||
Visit [Releases](https://github.com/farion1231/cc-switch/releases/latest) to download the appropriate version.
|
||||
|
||||
### System Requirements
|
||||
|
||||
| System | Minimum Version | Architecture |
|
||||
| ------- | ------------------------------- | ----------------------------------- |
|
||||
| Windows | Windows 10 or later | x64 |
|
||||
| macOS | macOS 10.15 (Catalina) or later | Intel (x64) / Apple Silicon (arm64) |
|
||||
| Linux | See table below | x64 |
|
||||
|
||||
### Windows
|
||||
|
||||
| File | Description |
|
||||
| ------------------------------------------ | ---------------------------------------------------- |
|
||||
| `CC-Switch-v3.12.2-Windows.msi` | **Recommended** - MSI installer with auto-update |
|
||||
| `CC-Switch-v3.12.2-Windows-Portable.zip` | Portable version, extract and run, no registry write |
|
||||
|
||||
### macOS
|
||||
|
||||
| File | Description |
|
||||
| ---------------------------------- | -------------------------------------------------------------------- |
|
||||
| `CC-Switch-v3.12.2-macOS.zip` | **Recommended** - Extract and drag to Applications, Universal Binary |
|
||||
| `CC-Switch-v3.12.2-macOS.tar.gz` | For Homebrew installation and auto-update |
|
||||
|
||||
> **Note**: Since the author doesn't have an Apple Developer account, you may see an "unidentified developer" warning on first launch. Please close it, then go to "System Settings" -> "Privacy & Security" -> click "Open Anyway", and it will open normally afterwards.
|
||||
|
||||
### Homebrew (macOS)
|
||||
|
||||
```bash
|
||||
brew tap farion1231/ccswitch
|
||||
brew install --cask cc-switch
|
||||
```
|
||||
|
||||
Update:
|
||||
|
||||
```bash
|
||||
brew upgrade --cask cc-switch
|
||||
```
|
||||
|
||||
### Linux
|
||||
|
||||
| Distribution | Recommended Format | Installation Method |
|
||||
| --------------------------------------- | ------------------ | ---------------------------------------------------------------------- |
|
||||
| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb` or `sudo apt install ./CC-Switch-*.deb` |
|
||||
| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm` or `sudo dnf install ./CC-Switch-*.rpm` |
|
||||
| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
|
||||
| Arch Linux / Manjaro | `.AppImage` | Add execute permission and run directly, or use AUR |
|
||||
| Other distributions / Unsure | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
|
||||
@@ -0,0 +1,138 @@
|
||||
# CC Switch v3.12.2
|
||||
|
||||
> プロキシテイクオーバー中の共通設定保護、Snippet ライフサイクルの安定化、Codex TOML セクション対応編集
|
||||
|
||||
**[中文版 →](v3.12.2-zh.md) | [English →](v3.12.2-en.md)**
|
||||
|
||||
---
|
||||
|
||||
## 概要
|
||||
|
||||
CC Switch v3.12.2 は、信頼性を重視したパッチリリースです。プロキシテイクオーバーモードでの共通設定(Common Config)の消失問題を解決し、Codex TOML 設定の編集精度を改善しました。テイクオーバーのホットスイッチとプロバイダー同期は、ライブ設定ファイルを上書きする代わりにリストアバックアップを更新するようになりました。起動シーケンスを再整理し、テイクオーバー状態を復元する前にクリーンなライブファイルから Snippet を抽出するようにしました。また Codex の `base_url` 編集をセクション対応モデルにリファクタリングし、ファイル末尾への誤追加を防止しました。
|
||||
|
||||
**リリース日**: 2026-03-12
|
||||
|
||||
**更新規模**: 5 commits | 22 files changed | +1,716 / -288 lines
|
||||
|
||||
---
|
||||
|
||||
## ハイライト
|
||||
|
||||
- **空状態ガイダンスの改善**: プロバイダーリストが空の場合に詳細なインポート手順を表示し、Claude/Codex/Gemini には共通設定 Snippet のヒントを条件付きで表示
|
||||
|
||||
- **プロキシテイクオーバーリストアフロー刷新**: ホットスイッチとプロバイダー同期がライブ設定ファイルの上書きではなくリストアバックアップの更新を行うようになり、ロールバック時に完全なユーザー設定を保持
|
||||
- **Snippet ライフサイクルの安定化**: `cleared` フラグを導入し、クリア済み Snippet の自動再抽出を防止。起動順序を調整してクリーンな状態から抽出
|
||||
- **Codex TOML セクション対応編集**: `base_url` と `model` フィールドの読み書きが正しい `[model_providers.<name>]` セクションを対象にするように改善
|
||||
- **Codex MCP 設定の保護**: プロバイダーホットスイッチ時にリストアスナップショット内の既存 `mcp_servers` ブロックが保持されるように修正。テーブル全体の置換からサーバー ID ごとのマージに変更し、プロバイダー/共通設定の MCP 定義が競合時に優先
|
||||
|
||||
---
|
||||
|
||||
## 新機能
|
||||
|
||||
### 空状態ガイダンスの改善
|
||||
|
||||
プロバイダーリストが空の場合の初回利用体験を改善しました。
|
||||
|
||||
- 空状態ページにプロバイダーインポートの操作ガイドを表示
|
||||
- Claude/Codex/Gemini アプリケーションに共通設定 Snippet のヒントを条件付きで表示(OpenCode/OpenClaw には非表示)
|
||||
|
||||
---
|
||||
|
||||
## 変更
|
||||
|
||||
### プロキシテイクオーバーリストアフロー
|
||||
|
||||
テイクオーバーのホットスイッチとプロバイダー同期ロジックをリファクタリングし、テイクオーバーライフサイクル全体で共通設定を保護します。
|
||||
|
||||
- テイクオーバーがアクティブな場合、プロバイダー同期がライブ設定ファイルへの直接書き込みではなくリストアバックアップを更新
|
||||
- リストアスナップショットの保存前に共通設定を適用した実効プロバイダー設定を再構築し、ロールバックで実際のユーザー設定を復元
|
||||
- 共通設定の使用が推測されるレガシープロバイダーに `commonConfigEnabled=true` を自動マーク
|
||||
|
||||
### Codex TOML 編集エンジン
|
||||
|
||||
Codex `config.toml` の更新ロジックを共有のセクション対応 TOML ヘルパーにリファクタリングしました。
|
||||
|
||||
- Rust 側に新モジュール `codex_config.rs` を追加(`update_codex_toml_field` と `remove_codex_toml_base_url_if`)
|
||||
- フロントエンドにセクション対応ユーティリティ `getTomlSectionRange` / `getCodexProviderSectionName` を追加
|
||||
- `proxy.rs` に散在していたインライン TOML 編集ロジックを新モジュールに委譲
|
||||
|
||||
### 共通設定初期化ライフサイクル
|
||||
|
||||
Snippet の抽出とマイグレーションをより堅牢にするため、起動シーケンスを再整理しました。
|
||||
|
||||
- 起動時にプロキシテイクオーバー状態を復元する前に、クリーンなライブファイルから共通設定 Snippet を自動抽出
|
||||
- Snippet の `cleared` フラグを導入し、ユーザーが意図的にクリアしたかどうかを追跡
|
||||
- 一回限りのレガシーマイグレーションフラグを永続化し、`commonConfigEnabled` のバックフィルの繰り返しを防止
|
||||
|
||||
---
|
||||
|
||||
## バグ修正
|
||||
|
||||
### 共通設定の消失
|
||||
|
||||
- プロキシテイクオーバー中に共通設定が消失する複数のシナリオを修正:同期によるライブファイルの上書き、ホットスイッチによる不完全なリストアスナップショット、プロバイダー切り替え時の設定変更の消失
|
||||
|
||||
### Codex リストアスナップショットの保護
|
||||
|
||||
- プロバイダーホットスイッチ時に Codex テイクオーバーリストアバックアップが既存の `mcp_servers` ブロックを破棄する問題を修正。MCP バックアップ保持をテーブル全体の置換からサーバー ID ごとのマージに変更し、プロバイダー/共通設定の MCP 更新が競合時に優先され、バックアップのみのサーバーも保持
|
||||
|
||||
### クリア済み Snippet の復活
|
||||
|
||||
- 起動時の自動抽出が、ユーザーが意図的にクリアした共通設定 Snippet を再作成する問題を修正
|
||||
|
||||
### Codex `base_url` の配置エラー
|
||||
|
||||
- Codex `base_url` の抽出と編集が正しい `[model_providers.<name>]` セクションを対象にせず、ファイル末尾に追加されたり `mcp_servers.*.base_url` をプロバイダーエンドポイントと誤認する問題を修正
|
||||
|
||||
---
|
||||
|
||||
## ダウンロードとインストール
|
||||
|
||||
[Releases](https://github.com/farion1231/cc-switch/releases/latest) から適切なバージョンをダウンロードしてください。
|
||||
|
||||
### システム要件
|
||||
|
||||
| システム | 最小バージョン | アーキテクチャ |
|
||||
| -------- | -------------------------------- | ----------------------------------- |
|
||||
| Windows | Windows 10 以降 | x64 |
|
||||
| macOS | macOS 10.15 (Catalina) 以降 | Intel (x64) / Apple Silicon (arm64) |
|
||||
| Linux | 下表参照 | x64 |
|
||||
|
||||
### Windows
|
||||
|
||||
| ファイル | 説明 |
|
||||
| ------------------------------------------ | ---------------------------------------------------- |
|
||||
| `CC-Switch-v3.12.2-Windows.msi` | **推奨** - MSI インストーラー、自動更新対応 |
|
||||
| `CC-Switch-v3.12.2-Windows-Portable.zip` | ポータブル版、解凍して実行、レジストリ書き込みなし |
|
||||
|
||||
### macOS
|
||||
|
||||
| ファイル | 説明 |
|
||||
| ---------------------------------- | ----------------------------------------------------------------- |
|
||||
| `CC-Switch-v3.12.2-macOS.zip` | **推奨** - 解凍して Applications にドラッグ、Universal Binary |
|
||||
| `CC-Switch-v3.12.2-macOS.tar.gz` | Homebrew インストールと自動更新用 |
|
||||
|
||||
> **注意**: 作者が Apple Developer アカウントを持っていないため、初回起動時に「開発元を確認できません」という警告が表示される場合があります。一度閉じてから、「システム設定」→「プライバシーとセキュリティ」→「このまま開く」をクリックすると、その後は正常に開けます。
|
||||
|
||||
### Homebrew (macOS)
|
||||
|
||||
```bash
|
||||
brew tap farion1231/ccswitch
|
||||
brew install --cask cc-switch
|
||||
```
|
||||
|
||||
更新:
|
||||
|
||||
```bash
|
||||
brew upgrade --cask cc-switch
|
||||
```
|
||||
|
||||
### Linux
|
||||
|
||||
| ディストリビューション | 推奨形式 | インストール方法 |
|
||||
| --------------------------------------- | ----------- | ---------------------------------------------------------------------- |
|
||||
| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb` または `sudo apt install ./CC-Switch-*.deb` |
|
||||
| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm` または `sudo dnf install ./CC-Switch-*.rpm` |
|
||||
| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
|
||||
| Arch Linux / Manjaro | `.AppImage` | 実行権限を追加して直接実行、または AUR を使用 |
|
||||
| その他のディストリビューション / 不明 | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
|
||||
@@ -0,0 +1,138 @@
|
||||
# CC Switch v3.12.2
|
||||
|
||||
> 代理接管期间通用配置保护、Snippet 生命周期稳定性、Codex TOML Section 感知编辑
|
||||
|
||||
**[English →](v3.12.2-en.md) | [日本語版 →](v3.12.2-ja.md)**
|
||||
|
||||
---
|
||||
|
||||
## 概览
|
||||
|
||||
CC Switch v3.12.2 是一个以可靠性为核心的补丁版本,重点解决代理(Proxy)接管模式下通用配置(Common Config)丢失的问题,并改进了 Codex TOML 配置的编辑准确性。代理接管的热切换和供应商同步现在会更新恢复备份而非直接覆盖 live 文件;启动流程重新排序,确保先从干净的 live 文件提取 Snippet 再恢复接管状态;Codex 的 `base_url` 编辑重构为 Section 感知模式,不再错误追加到文件末尾。
|
||||
|
||||
**发布日期**:2026-03-12
|
||||
|
||||
**更新规模**:5 commits | 22 files changed | +1,716 / -288 lines
|
||||
|
||||
---
|
||||
|
||||
## 重点内容
|
||||
|
||||
- **首次使用引导优化**:供应商列表空状态显示详细的导入说明,Claude/Codex/Gemini 还会提示通用配置 Snippet 功能
|
||||
|
||||
- **代理接管恢复流程重构**:热切换和供应商同步现在刷新恢复备份,而非覆盖 live 配置文件,回滚时保留完整的用户配置
|
||||
- **Snippet 生命周期稳定**:引入 `cleared` 标志防止已清除的 Snippet 被自动重新提取,启动顺序调整确保从干净状态提取
|
||||
- **Codex TOML Section 感知编辑**:`base_url` 和 `model` 字段的读写现在定位到正确的 `[model_providers.<name>]` Section
|
||||
- **Codex MCP 配置保护**:热切换供应商时保留恢复快照中已有的 `mcp_servers` 配置块,按 server id 合并而非整表替换,供应商/通用配置的 MCP 定义优先
|
||||
|
||||
---
|
||||
|
||||
## 新功能
|
||||
|
||||
### 空状态引导优化
|
||||
|
||||
改善首次使用体验,当供应商列表为空时显示详细的导入说明。
|
||||
|
||||
- 空状态页面展示导入供应商的操作指引
|
||||
- 对 Claude/Codex/Gemini 应用有条件地显示通用配置 Snippet 提示(OpenCode/OpenClaw 不显示)
|
||||
|
||||
---
|
||||
|
||||
## 变更
|
||||
|
||||
### 代理接管恢复流程
|
||||
|
||||
代理接管的热切换和供应商同步逻辑经过重构,确保通用配置在整个接管生命周期中得到保护。
|
||||
|
||||
- 接管活跃时,供应商同步更新恢复备份而非直接写入 live 配置文件
|
||||
- 保存恢复快照前先应用通用配置,使回滚能还原真实的用户配置
|
||||
- 遗留供应商中推断使用了通用配置的条目自动标记 `commonConfigEnabled=true`
|
||||
|
||||
### Codex TOML 编辑引擎
|
||||
|
||||
将 Codex `config.toml` 的更新逻辑重构到共享的 Section 感知 TOML 辅助函数上。
|
||||
|
||||
- Rust 端新增 `codex_config.rs` 模块,包含 `update_codex_toml_field` 和 `remove_codex_toml_base_url_if`
|
||||
- 前端新增 `getTomlSectionRange` / `getCodexProviderSectionName` 等 Section 感知工具函数
|
||||
- `proxy.rs` 中散落的 TOML 内联编辑逻辑统一委托给新模块
|
||||
|
||||
### 通用配置初始化生命周期
|
||||
|
||||
启动流程重新排序,通用配置 Snippet 的提取和迁移逻辑更加健壮。
|
||||
|
||||
- 启动时先从干净的 live 文件自动提取通用配置 Snippet,再恢复代理接管状态
|
||||
- 引入 Snippet `cleared` 标志,追踪用户是否主动清除了某个 Snippet
|
||||
- 持久化一次性遗留迁移标志,避免重复执行旧版 `commonConfigEnabled` 回填
|
||||
|
||||
---
|
||||
|
||||
## Bug 修复
|
||||
|
||||
### 通用配置丢失
|
||||
|
||||
- 修复代理接管期间通用配置可能被丢弃的多种场景:同步覆盖 live 文件、热切换产生不完整的恢复快照、供应商切换丢失配置变更
|
||||
|
||||
### Codex 恢复快照保护
|
||||
|
||||
- 修复 Codex 接管恢复备份在供应商热切换时丢弃已有 `mcp_servers` 配置块的问题;将 MCP 备份保留策略从整表替换改为按 server id 合并,供应商/通用配置的 MCP 定义在冲突时优先,备份中独有的服务器仍被保留
|
||||
|
||||
### 已清除 Snippet 复活
|
||||
|
||||
- 修复启动时自动提取机制重新创建用户已主动清除的通用配置 Snippet 的问题
|
||||
|
||||
### Codex `base_url` 位置错误
|
||||
|
||||
- 修复 Codex `base_url` 提取和编辑未定位到正确的 `[model_providers.<name>]` Section,导致追加到文件末尾或误将 `mcp_servers.*.base_url` 识别为供应商端点的问题
|
||||
|
||||
---
|
||||
|
||||
## 下载与安装
|
||||
|
||||
访问 [Releases](https://github.com/farion1231/cc-switch/releases/latest) 下载对应版本。
|
||||
|
||||
### 系统要求
|
||||
|
||||
| 系统 | 最低版本 | 架构 |
|
||||
| ------- | ----------------------------- | ----------------------------------- |
|
||||
| Windows | Windows 10 及以上 | x64 |
|
||||
| macOS | macOS 10.15 (Catalina) 及以上 | Intel (x64) / Apple Silicon (arm64) |
|
||||
| Linux | 见下表 | x64 |
|
||||
|
||||
### Windows
|
||||
|
||||
| 文件 | 说明 |
|
||||
| ------------------------------------------ | ----------------------------------- |
|
||||
| `CC-Switch-v3.12.2-Windows.msi` | **推荐** - MSI 安装包,支持自动更新 |
|
||||
| `CC-Switch-v3.12.2-Windows-Portable.zip` | 便携版,解压即用,不写入注册表 |
|
||||
|
||||
### macOS
|
||||
|
||||
| 文件 | 说明 |
|
||||
| ---------------------------------- | --------------------------------------------------------- |
|
||||
| `CC-Switch-v3.12.2-macOS.zip` | **推荐** - 解压后拖入 Applications 即可,Universal Binary |
|
||||
| `CC-Switch-v3.12.2-macOS.tar.gz` | 用于 Homebrew 安装和自动更新 |
|
||||
|
||||
> **注意**:由于作者没有苹果开发者账号,首次打开可能出现"未知开发者"警告,请先关闭,然后前往"系统设置" → "隐私与安全性" → 点击"仍要打开",之后便可以正常打开
|
||||
|
||||
### Homebrew(macOS)
|
||||
|
||||
```bash
|
||||
brew tap farion1231/ccswitch
|
||||
brew install --cask cc-switch
|
||||
```
|
||||
|
||||
更新:
|
||||
|
||||
```bash
|
||||
brew upgrade --cask cc-switch
|
||||
```
|
||||
|
||||
### Linux
|
||||
|
||||
| 发行版 | 推荐格式 | 安装方式 |
|
||||
| --------------------------------------- | ----------- | ---------------------------------------------------------------------- |
|
||||
| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb` 或 `sudo apt install ./CC-Switch-*.deb` |
|
||||
| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm` 或 `sudo dnf install ./CC-Switch-*.rpm` |
|
||||
| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
|
||||
| Arch Linux / Manjaro | `.AppImage` | 添加执行权限后直接运行,或使用 AUR |
|
||||
| 其他发行版 / 不确定 | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
|
||||
@@ -0,0 +1,313 @@
|
||||
# CC Switch v3.12.3
|
||||
|
||||
> GitHub Copilot Reverse Proxy, macOS Code Signing & Notarization, Reasoning Effort Mapping, OpenCode SQLite Backend
|
||||
|
||||
**[中文版 →](v3.12.3-zh.md) | [日本語版 →](v3.12.3-ja.md)**
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
CC Switch v3.12.3 is a major feature release that adds GitHub Copilot reverse proxy support with a dedicated Auth Center, introduces macOS code signing and Apple notarization for a seamless install experience, maps reasoning effort levels across providers, migrates OpenCode to a SQLite backend, enables Tool Search via the native `ENABLE_TOOL_SEARCH` environment variable toggle, and delivers a full skill backup/restore lifecycle. Additional improvements include proxy gzip compression, o-series model compatibility, Skills import rework, Ghostty terminal fix, Skills cache strategy optimization, Claude 4.6 context window update, and multiple bug fixes.
|
||||
|
||||
**Release Date**: 2026-03-24
|
||||
|
||||
**Update Scale**: 36 commits | 107 files changed | +9,124 / -802 lines
|
||||
|
||||
---
|
||||
|
||||
## Highlights
|
||||
|
||||
- **GitHub Copilot reverse proxy**: Full Copilot proxy support with OAuth device flow authentication, token refresh, and request fingerprint emulation ([⚠️ Risk Notice](#️-risk-notice))
|
||||
- **Copilot Auth Center**: Dedicated authentication management UI for GitHub Copilot OAuth flow with token status display and one-click refresh
|
||||
- **macOS code signing & notarization**: macOS builds are now code-signed and notarized by Apple, eliminating the "unidentified developer" warning entirely
|
||||
- **Reasoning Effort mapping**: Proxy-layer auto-mapping — explicit `output_config.effort` takes priority, falling back to `budget_tokens` thresholds (<4 000→low, 4 000–16 000→medium, ≥16 000→high) for o-series and GPT-5+ models
|
||||
- **OpenCode SQLite backend**: Added SQLite session storage for OpenCode alongside existing JSON backend; dual-backend scan with SQLite priority on ID conflicts
|
||||
- **Codex 1M context window toggle**: One-click checkbox to set `model_context_window = 1000000` with auto-populated `model_auto_compact_token_limit`
|
||||
- **Disable Auto-Upgrade toggle**: Added `DISABLE_AUTOUPDATER` env var checkbox in the Claude Common Config editor to prevent Claude Code from auto-upgrading
|
||||
- **Tool Search env var toggle**: Tool Search enabled via Claude 2.1.76+ native `ENABLE_TOOL_SEARCH` environment variable in the Common Config editor — no binary patching required
|
||||
- **Skill backup/restore lifecycle**: Skills are automatically backed up before uninstall; backup list with restore and delete management added
|
||||
- **Proxy gzip compression**: Non-streaming proxy requests now auto-negotiate gzip compression, reducing bandwidth usage
|
||||
- **o-series model compatibility**: Chat Completions proxy correctly uses `max_completion_tokens` for o1/o3/o4-mini models; Responses API kept on the correct `max_output_tokens` field
|
||||
- **Skills import rework**: Replaced implicit filesystem-based app inference with explicit `ImportSkillSelection` to prevent incorrect multi-app activation
|
||||
- **Ghostty terminal support**: Fixed Claude session restore in Ghostty terminal
|
||||
|
||||
---
|
||||
|
||||
## New Features
|
||||
|
||||
### GitHub Copilot Reverse Proxy
|
||||
|
||||
Added full reverse proxy support for GitHub Copilot, enabling Copilot-authenticated requests to be forwarded through CC Switch.
|
||||
|
||||
- Implements OAuth device flow authentication for GitHub Copilot
|
||||
- Automatic token refresh and session management
|
||||
- Request fingerprint emulation for seamless compatibility
|
||||
- Integrated into the existing proxy infrastructure alongside Claude, Codex, and Gemini handlers
|
||||
|
||||
### Copilot Auth Center
|
||||
|
||||
A dedicated authentication management UI for GitHub Copilot.
|
||||
|
||||
- OAuth device flow with code display and browser-based authorization
|
||||
- Token status display showing expiration and validity
|
||||
- One-click token refresh without re-authentication
|
||||
- Integrated into the settings panel for easy access
|
||||
|
||||
### Reasoning Effort Mapping
|
||||
|
||||
Proxy-layer auto-mapping of reasoning effort for OpenAI o-series and GPT-5+ models.
|
||||
|
||||
- Two-tier resolution: explicit `output_config.effort` takes priority, falling back to thinking `budget_tokens` thresholds (<4 000→low, 4 000–16 000→medium, ≥16 000→high)
|
||||
- Covers both Chat Completions and Responses API paths with 17 unit tests
|
||||
|
||||
### OpenCode SQLite Backend
|
||||
|
||||
Added SQLite session storage support for OpenCode alongside the existing JSON backend.
|
||||
|
||||
- Dual-backend scan with SQLite priority on ID conflicts
|
||||
- Atomic session deletion and path validation
|
||||
- JSON backend remains functional for backwards compatibility
|
||||
|
||||
### Codex 1M Context Window Toggle
|
||||
|
||||
Added a one-click toggle for Codex 1M context window in the config editor.
|
||||
|
||||
- Checkbox sets `model_context_window = 1000000` in `config.toml`
|
||||
- Auto-populates `model_auto_compact_token_limit = 900000` when enabled
|
||||
- Unchecking removes both fields cleanly
|
||||
|
||||
### Disable Auto-Upgrade Toggle
|
||||
|
||||
Added a checkbox in the Claude Common Config editor to disable Claude Code auto-upgrades.
|
||||
|
||||
- Sets `DISABLE_AUTOUPDATER=1` in the environment configuration when enabled
|
||||
- Displayed alongside Teammates mode, Tool Search, and High Effort toggles
|
||||
|
||||
### Tool Search Environment Variable Toggle
|
||||
|
||||
Tool Search is now enabled via the native `ENABLE_TOOL_SEARCH` environment variable introduced in Claude 2.1.76+.
|
||||
|
||||
- Toggle available in the Common Config editor under environment variables
|
||||
- Sets `ENABLE_TOOL_SEARCH=1` in the Claude environment configuration
|
||||
- No binary patching required — uses Claude's built-in support
|
||||
|
||||
### macOS Code Signing & Notarization
|
||||
|
||||
macOS builds are now code-signed and notarized by Apple.
|
||||
|
||||
- Application signed with a valid Apple Developer certificate
|
||||
- Notarized through Apple's notarization service for Gatekeeper approval
|
||||
- DMG installer also signed and notarized
|
||||
- Eliminates the "unidentified developer" warning on first launch
|
||||
|
||||
### Skill Auto-Backup on Uninstall
|
||||
|
||||
Skill files are now automatically backed up before uninstall to prevent accidental data loss.
|
||||
|
||||
- Backups stored in `~/.cc-switch/skill-backups/` with all skill files and a `meta.json` containing original metadata
|
||||
- Old backups are automatically pruned to keep at most 20
|
||||
- Backup path is returned to the frontend and shown in the success toast
|
||||
|
||||
### Skill Backup Restore & Delete
|
||||
|
||||
Added management commands for skill backups created during uninstall.
|
||||
|
||||
- List all available skill backups with metadata
|
||||
- Restore copies files back to SSOT, saves the DB record, and syncs to the current app with rollback on failure
|
||||
- Delete removes the backup directory after a confirmation dialog
|
||||
- ConfirmDialog gains a configurable zIndex prop to support nested dialog stacking
|
||||
|
||||
---
|
||||
|
||||
## Changes
|
||||
|
||||
### Skills Cache Strategy Optimization
|
||||
|
||||
Optimized the Skills cache invalidation strategy for better performance.
|
||||
|
||||
- Reduced unnecessary cache refreshes during skill operations
|
||||
- Improved cache coherence between skill install/uninstall and list queries
|
||||
|
||||
### Claude 4.6 Context Window Update
|
||||
|
||||
Updated Claude 4.6 model preset with the latest context window size.
|
||||
|
||||
- Reflects the expanded context window for Claude 4.6 models
|
||||
- Updated in provider presets for accurate model information display
|
||||
|
||||
### MiniMax M2.7 Upgrade
|
||||
|
||||
- Updated MiniMax provider preset to M2.7 model variant
|
||||
|
||||
### Xiaomi MiMo Upgrade
|
||||
|
||||
- Updated Xiaomi MiMo provider preset to the latest model version
|
||||
|
||||
### AddProviderDialog Simplification
|
||||
|
||||
- Removed redundant OAuth tab, reducing dialog from 3 tabs to 2 (app-specific + universal)
|
||||
|
||||
### Provider Form Advanced Options Collapse
|
||||
|
||||
- Model mapping, API format, and other advanced fields in the Claude provider form now auto-collapse when empty
|
||||
- Auto-expands when any value is set or when a preset fills them in; does not auto-collapse when manually cleared
|
||||
|
||||
### Proxy Gzip Compression
|
||||
|
||||
Non-streaming proxy requests now support gzip compression for reduced bandwidth usage.
|
||||
|
||||
- Non-streaming requests let reqwest auto-negotiate gzip and transparently decompress responses
|
||||
- Streaming requests conservatively keep `Accept-Encoding: identity` to avoid decompression errors on interrupted SSE streams
|
||||
|
||||
### o1/o3 Model Compatibility
|
||||
|
||||
Proxy forwarding now handles OpenAI o-series model token parameters correctly.
|
||||
|
||||
- Chat Completions path uses `max_completion_tokens` instead of `max_tokens` for o1/o3/o4-mini models (#1451, thanks @Hemilt0n)
|
||||
- Responses API path kept on the correct `max_output_tokens` field instead of incorrectly injecting `max_completion_tokens`
|
||||
|
||||
### OpenCode Model Variants
|
||||
|
||||
- Placed OpenCode model variants at top level instead of inside options for better discoverability (#1317)
|
||||
|
||||
### Skills Import Flow
|
||||
|
||||
The Skills import flow has been reworked for correctness and cleanup.
|
||||
|
||||
- Replaced implicit filesystem-based app inference with explicit `ImportSkillSelection` to prevent incorrect multi-app activation when the same skill directory exists under multiple app paths
|
||||
- Added reconciliation to `sync_to_app` to remove disabled/orphaned symlinks
|
||||
- MCP `sync_all_enabled` now removes disabled servers from live config
|
||||
- Schema migration preserves a snapshot of legacy app mappings to avoid lossy reconstruction
|
||||
|
||||
---
|
||||
|
||||
## Bug Fixes
|
||||
|
||||
### WebDAV Password Clearing
|
||||
|
||||
- Fixed an issue where the WebDAV password was silently cleared when saving unrelated settings
|
||||
|
||||
### Tool Message Parsing
|
||||
|
||||
- Fixed incorrect parsing of tool-use messages in certain proxy response formats
|
||||
|
||||
### Dark Mode Styling
|
||||
|
||||
- Fixed dark mode rendering inconsistencies in UI components
|
||||
|
||||
### Copilot Request Fingerprint
|
||||
|
||||
- Fixed request fingerprint generation for Copilot proxy to match expected format
|
||||
|
||||
### Provider Form Double Submit
|
||||
|
||||
- Prevented duplicate submissions on rapid button clicks in provider add/edit forms (#1352, thanks @Hexi1997)
|
||||
|
||||
### Ghostty Session Restore
|
||||
|
||||
- Fixed Claude session restore in Ghostty terminal (#1506, thanks @canyonsehun)
|
||||
|
||||
### Skill ZIP Import Extension
|
||||
|
||||
- Added `.skill` file extension support in ZIP import dialog (#1240, #1455, thanks @yovinchen)
|
||||
|
||||
### Skill ZIP Install Target App
|
||||
|
||||
- ZIP skill installs now use the currently active app instead of always defaulting to Claude
|
||||
|
||||
### OpenClaw Active Card Highlight
|
||||
|
||||
- Fixed active OpenClaw provider card not being highlighted (#1419, thanks @funnytime75)
|
||||
|
||||
### Responsive Layout with TOC
|
||||
|
||||
- Improved responsive design when TOC title exists (#1491, thanks @West-Pavilion)
|
||||
|
||||
### Import Skills Dialog White Screen
|
||||
|
||||
- Added missing TooltipProvider in ImportSkillsDialog to prevent runtime crash when opening the dialog
|
||||
|
||||
### Panel Bottom Blank Area
|
||||
|
||||
- Replaced hardcoded `h-[calc(100vh-8rem)]` with `flex-1 min-h-0` across all content panels to eliminate bottom gap caused by mismatched offset values on different platforms
|
||||
|
||||
---
|
||||
|
||||
## Documentation
|
||||
|
||||
### Pricing Model ID Normalization
|
||||
|
||||
- Added documentation section explaining model ID normalization rules (prefix stripping, suffix trimming, `@`→`-` replacement) in EN/ZH/JA user manuals (#1591, thanks @makoMakoGo)
|
||||
|
||||
### macOS Signed Build Messaging
|
||||
|
||||
- Removed all `xattr` workaround instructions and "unidentified developer" warnings from README, README_ZH, installation guides (EN/ZH/JA), and FAQ pages (EN/ZH/JA); replaced with "signed and notarized by Apple" messaging
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ Risk Notice
|
||||
|
||||
**GitHub Copilot Reverse Proxy Disclaimer**
|
||||
|
||||
The Copilot reverse proxy feature introduced in this release accesses GitHub Copilot services through reverse-engineered, unofficial APIs. Please be aware of the following risks before enabling this feature:
|
||||
|
||||
1. **Terms of Service**: This feature may violate [GitHub's Acceptable Use Policies](https://docs.github.com/en/site-policy/acceptable-use-policies/github-acceptable-use-policies) and [Terms for Additional Products and Features](https://docs.github.com/en/site-policy/github-terms/github-terms-for-additional-products-and-features), which prohibit excessive automated bulk activity, unauthorized service reproduction, and placing undue burden on servers through automated means.
|
||||
2. **Account Risk**: There are documented cases of GitHub issuing warning emails to users of similar tools, citing "scripted interactions or otherwise deliberately unusual or strenuous" usage patterns. Continued use after a warning may result in temporary or permanent suspension of Copilot access.
|
||||
3. **No Guarantee**: GitHub may update its detection mechanisms at any time, and usage patterns that work today may be flagged in the future.
|
||||
|
||||
Users enable this feature **at their own risk**. CC Switch is not responsible for any account restrictions, warnings, or service suspensions resulting from the use of this feature.
|
||||
|
||||
---
|
||||
|
||||
## Download & Installation
|
||||
|
||||
Visit [Releases](https://github.com/farion1231/cc-switch/releases/latest) to download the appropriate version.
|
||||
|
||||
### System Requirements
|
||||
|
||||
| System | Minimum Version | Architecture |
|
||||
| ------- | ------------------------------- | ----------------------------------- |
|
||||
| Windows | Windows 10 or later | x64 |
|
||||
| macOS | macOS 12 (Monterey) or later | Intel (x64) / Apple Silicon (arm64) |
|
||||
| Linux | See table below | x64 |
|
||||
|
||||
### Windows
|
||||
|
||||
| File | Description |
|
||||
| ------------------------------------------ | ---------------------------------------------------- |
|
||||
| `CC-Switch-v3.12.3-Windows.msi` | **Recommended** - MSI installer with auto-update |
|
||||
| `CC-Switch-v3.12.3-Windows-Portable.zip` | Portable version, extract and run, no registry write |
|
||||
|
||||
### macOS
|
||||
|
||||
| File | Description |
|
||||
| ---------------------------------- | -------------------------------------------------------------------- |
|
||||
| `CC-Switch-v3.12.3-macOS.dmg` | **Recommended** - DMG installer, drag to Applications, Universal Binary |
|
||||
| `CC-Switch-v3.12.3-macOS.zip` | ZIP archive, extract and drag to Applications, Universal Binary |
|
||||
| `CC-Switch-v3.12.3-macOS.tar.gz` | For Homebrew installation and auto-update |
|
||||
|
||||
> macOS builds are code-signed and notarized by Apple for a seamless install experience.
|
||||
|
||||
### Homebrew (macOS)
|
||||
|
||||
```bash
|
||||
brew tap farion1231/ccswitch
|
||||
brew install --cask cc-switch
|
||||
```
|
||||
|
||||
Update:
|
||||
|
||||
```bash
|
||||
brew upgrade --cask cc-switch
|
||||
```
|
||||
|
||||
### Linux
|
||||
|
||||
| Distribution | Recommended Format | Installation Method |
|
||||
| --------------------------------------- | ------------------ | ---------------------------------------------------------------------- |
|
||||
| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb` or `sudo apt install ./CC-Switch-*.deb` |
|
||||
| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm` or `sudo dnf install ./CC-Switch-*.rpm` |
|
||||
| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
|
||||
| Arch Linux / Manjaro | `.AppImage` | Add execute permission and run directly, or use AUR |
|
||||
| Other distributions / Unsure | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
|
||||
@@ -0,0 +1,313 @@
|
||||
# CC Switch v3.12.3
|
||||
|
||||
> GitHub Copilot リバースプロキシ、macOS コード署名と公証、Reasoning Effort マッピング、Tool Search 環境変数トグル、Skill バックアップ/リストア、OpenCode SQLite バックエンド
|
||||
|
||||
**[中文版 →](v3.12.3-zh.md) | [English →](v3.12.3-en.md)**
|
||||
|
||||
---
|
||||
|
||||
## 概要
|
||||
|
||||
CC Switch v3.12.3 は、GitHub Copilot リバースプロキシと Copilot Auth Center を追加し、Copilot トークンを使用した Claude/OpenAI API へのアクセスを実現しました。macOS ビルドに Apple コード署名と公証を導入し、「開発元を確認できません」の警告を解消しました。Reasoning Effort マッピングにより、Claude の thinking budget を OpenAI 互換の reasoning_effort パラメータに自動変換します。Tool Search は従来のバイナリパッチ方式から Claude 2.1.76+ ネイティブの `ENABLE_TOOL_SEARCH` 環境変数トグルに移行し、共通設定エディタから切り替え可能になりました。OpenCode バックエンドを JSON から SQLite に移行し、Skill バックアップ/リストアライフサイクル、プロキシ gzip 圧縮、o シリーズモデル互換性の改善も含まれます。
|
||||
|
||||
**リリース日**: 2026-03-24
|
||||
|
||||
**更新規模**: 36 commits | 107 files changed | +9,124 / -802 lines
|
||||
|
||||
---
|
||||
|
||||
## ハイライト
|
||||
|
||||
- **GitHub Copilot リバースプロキシ**: Copilot トークンを使用して Claude/OpenAI API にアクセスするリバースプロキシを追加。Copilot Auth Center でトークンの取得と管理が可能([⚠️ リスクに関する注意事項](#️-リスクに関する注意事項))
|
||||
- **macOS コード署名と公証**: macOS ビルドが Apple のコード署名と公証に対応し、初回起動時の警告なしでインストール可能に。DMG インストーラーを新たに提供
|
||||
- **Reasoning Effort マッピング**: プロキシ層での自動マッピング — 明示的な `output_config.effort` を優先し、`budget_tokens` 閾値(<4000→low, 4000–16000→medium, ≥16000→high)にフォールバック。o シリーズおよび GPT-5+ モデルに対応
|
||||
- **Tool Search 環境変数トグル**: バイナリパッチ方式を廃止し、Claude 2.1.76+ ネイティブの `ENABLE_TOOL_SEARCH` 環境変数による切り替えに移行。共通設定エディタから設定可能
|
||||
- **Skill バックアップ/リストアライフサイクル**: アンインストール前に Skill ファイルを自動バックアップ。バックアップリスト、リストア、削除の管理機能を追加
|
||||
- **OpenCode SQLite バックエンド**: OpenCode に SQLite セッションストレージを追加(既存の JSON バックエンドと併存)。ID 競合時は SQLite を優先するデュアルバックエンドスキャン
|
||||
- **Codex 1M コンテキストウィンドウトグル**: 設定エディタでワンクリックで `model_context_window = 1000000` を設定可能。`model_auto_compact_token_limit` も自動設定
|
||||
- **自動アップグレード無効化トグル**: Claude 共通設定エディタに `DISABLE_AUTOUPDATER` 環境変数のチェックボックスを追加し、Claude Code の自動アップグレードを防止
|
||||
- **プロキシ Gzip 圧縮**: 非ストリーミングプロキシリクエストが gzip 圧縮を自動ネゴシエーションし、帯域幅消費を削減
|
||||
- **o シリーズモデル互換性**: Chat Completions プロキシが o1/o3/o4-mini モデルに `max_completion_tokens` を正しく使用。Responses API は正しい `max_output_tokens` フィールドを維持
|
||||
- **Skills インポートの刷新**: ファイルシステムベースの暗黙的なアプリ推論を明示的な `ImportSkillSelection` に置き換え、複数アプリの誤った有効化を防止
|
||||
- **Ghostty ターミナルサポート**: Ghostty ターミナルでの Claude セッション復元を修正
|
||||
|
||||
---
|
||||
|
||||
## 新機能
|
||||
|
||||
### GitHub Copilot リバースプロキシ
|
||||
|
||||
GitHub Copilot トークンを使用して Claude API および OpenAI API にアクセスするリバースプロキシ機能を追加しました。
|
||||
|
||||
- Copilot のアクセストークンを利用し、Claude Code や Codex などのクライアントからプロキシ経由で API リクエストを転送
|
||||
- Copilot 固有のリクエストフィンガープリントとヘッダー処理に対応
|
||||
- プロバイダープリセットに Copilot 用テンプレートを追加
|
||||
|
||||
### Copilot Auth Center
|
||||
|
||||
Copilot トークンの取得と管理を行う認証センターを追加しました。
|
||||
|
||||
- GitHub デバイスフローによるトークン取得をサポート
|
||||
- トークンの有効期限管理と自動リフレッシュ
|
||||
- フロントエンドから直接トークンステータスの確認と再認証が可能
|
||||
|
||||
### Reasoning Effort マッピング
|
||||
|
||||
OpenAI o シリーズおよび GPT-5+ モデル向けのプロキシ層自動マッピング機能を追加しました。
|
||||
|
||||
- 二段階の解決ロジック:明示的な `output_config.effort` を優先し、thinking `budget_tokens` 閾値(<4000→low, 4000–16000→medium, ≥16000→high)にフォールバック
|
||||
- Chat Completions と Responses API の両パスをカバー、17 個のユニットテスト付き
|
||||
|
||||
### Tool Search 環境変数トグル
|
||||
|
||||
Claude CLI Tool Search の有効化/無効化を環境変数で制御する設定を追加しました。
|
||||
|
||||
- Claude 2.1.76+ で導入されたネイティブの `ENABLE_TOOL_SEARCH` 環境変数を使用
|
||||
- 共通設定(Common Config)エディタから直接トグル可能
|
||||
- 従来のバイナリパッチ方式は不要になり、CLI アップデート時の再適用も不要
|
||||
|
||||
### Skill アンインストール時の自動バックアップ
|
||||
|
||||
アンインストール前に Skill ファイルを自動バックアップし、意図しないデータ損失を防止します。
|
||||
|
||||
- バックアップは `~/.cc-switch/skill-backups/` に保存され、すべての skill ファイルと元のメタデータを含む `meta.json` が含まれます
|
||||
- 古いバックアップは自動的にプルーニングされ、最大 20 個を保持
|
||||
- バックアップパスはフロントエンドに返され、成功トーストに表示
|
||||
|
||||
### Skill バックアップのリストアと削除
|
||||
|
||||
アンインストール時に作成された Skill バックアップの管理コマンドを追加しました。
|
||||
|
||||
- すべての利用可能な skill バックアップをメタデータ付きで一覧表示
|
||||
- リストアはファイルを SSOT にコピーし、DB レコードを保存し、現在のアプリに同期。失敗時は自動ロールバック
|
||||
- 削除は確認ダイアログの後にバックアップディレクトリを削除
|
||||
- ConfirmDialog にネストされたダイアログスタッキングをサポートする設定可能な zIndex プロパティを追加
|
||||
|
||||
### OpenCode SQLite バックエンド
|
||||
|
||||
OpenCode に SQLite セッションストレージサポートを追加しました(既存の JSON バックエンドと併存)。
|
||||
|
||||
- デュアルバックエンドスキャン、ID 競合時は SQLite を優先
|
||||
- アトミックなセッション削除とパス検証
|
||||
- JSON バックエンドは後方互換性のため引き続き機能
|
||||
|
||||
### Codex 1M コンテキストウィンドウトグル
|
||||
|
||||
設定エディタに Codex 1M コンテキストウィンドウのワンクリックトグルを追加しました。
|
||||
|
||||
- チェックボックスで `config.toml` に `model_context_window = 1000000` を設定
|
||||
- 有効化時に `model_auto_compact_token_limit = 900000` を自動設定
|
||||
- 無効化時は両フィールドをクリーンに削除
|
||||
|
||||
### 自動アップグレード無効化トグル
|
||||
|
||||
Claude 共通設定エディタに自動アップグレードを無効化するチェックボックスを追加しました。
|
||||
|
||||
- 有効化時に `DISABLE_AUTOUPDATER=1` 環境変数を設定し、Claude Code の自動アップグレードを防止
|
||||
- Teammates モード、Tool Search、高強度思考トグルと同じ行に表示
|
||||
|
||||
### macOS コード署名と公証
|
||||
|
||||
macOS ビルドに Apple のコード署名と公証を導入しました。
|
||||
|
||||
- Apple Developer ID による署名と Apple 公証サービスによる公証を実施
|
||||
- 初回起動時の「開発元を確認できません」警告が不要に
|
||||
- DMG インストーラーを新たに提供し、ドラッグ&ドロップでのインストールに対応
|
||||
- CI/CD パイプラインに署名・公証ステップを統合
|
||||
|
||||
---
|
||||
|
||||
## 変更
|
||||
|
||||
### Skills キャッシュ戦略の最適化
|
||||
|
||||
Skills のキャッシュ戦略を最適化し、パフォーマンスと信頼性を向上しました。
|
||||
|
||||
- キャッシュの有効期限管理とインバリデーション戦略を改善
|
||||
- 不要なキャッシュ再構築を削減し、起動時間を短縮
|
||||
|
||||
### Claude 4.6 コンテキストウィンドウ更新
|
||||
|
||||
Claude 4.6 モデルのコンテキストウィンドウサイズを更新しました。
|
||||
|
||||
- Claude 4.6 の最新コンテキストウィンドウサイズをプリセットに反映
|
||||
|
||||
### MiniMax M2.7 アップグレード
|
||||
|
||||
MiniMax モデルプリセットを M2.7 にアップグレードしました。
|
||||
|
||||
- MiniMax プロバイダープリセットのモデル ID とパラメータを M2.7 に更新
|
||||
|
||||
### Xiaomi MiMo アップグレード
|
||||
|
||||
Xiaomi MiMo モデルプリセットをアップグレードしました。
|
||||
|
||||
- MiMo プロバイダープリセットのモデル ID とパラメータを最新版に更新
|
||||
|
||||
### AddProviderDialog の簡素化
|
||||
|
||||
- 冗長な OAuth タブを削除し、ダイアログを 3 タブから 2 タブ(アプリ固有 + ユニバーサル)に簡素化
|
||||
|
||||
### プロバイダーフォームの高度なオプション折りたたみ
|
||||
|
||||
- Claude プロバイダーフォームのモデルマッピング、API フォーマットなどの高度なフィールドが未入力時にデフォルトで折りたたまれるように変更
|
||||
- プリセットが値を入力すると自動展開。手動クリア時は自動折りたたみしない
|
||||
|
||||
### プロキシ Gzip 圧縮
|
||||
|
||||
非ストリーミングプロキシリクエストが gzip 圧縮をサポートし、帯域幅消費を削減しました。
|
||||
|
||||
- 非ストリーミングリクエストは reqwest が gzip を自動ネゴシエーションし、レスポンスを透過的に解凍
|
||||
- ストリーミングリクエストは中断された SSE ストリームの解凍エラーを避けるため、保守的に `Accept-Encoding: identity` を維持
|
||||
|
||||
### o1/o3 モデル互換性
|
||||
|
||||
プロキシ転送が OpenAI o シリーズモデルのトークンパラメータを正しく処理するようになりました。
|
||||
|
||||
- Chat Completions パスが o1/o3/o4-mini モデルに `max_tokens` の代わりに `max_completion_tokens` を使用 (#1451、@Hemilt0n に感謝)
|
||||
- Responses API パスが正しい `max_output_tokens` フィールドを維持し、`max_completion_tokens` の誤った注入を防止
|
||||
|
||||
### OpenCode モデルバリアント
|
||||
|
||||
- OpenCode のモデルバリアントを options 内部ではなくプリセットのトップレベルに配置し、発見しやすさを向上 (#1317)
|
||||
|
||||
### Skills インポートフロー
|
||||
|
||||
Skills インポートフローが正確性とクリーンアップのためにリワークされました。
|
||||
|
||||
- ファイルシステムベースの暗黙的なアプリ推論を明示的な `ImportSkillSelection` に置き換え、同じ skill ディレクトリが複数アプリパスに存在する場合の複数アプリ誤有効化を防止
|
||||
- `sync_to_app` に調整ロジックを追加し、無効化/孤立したシンボリックリンクを削除
|
||||
- MCP `sync_all_enabled` がライブ設定から無効化されたサーバーを削除するように改善
|
||||
- スキーママイグレーションがレガシーアプリマッピングのスナップショットを保持し、損失のある再構築を回避
|
||||
|
||||
---
|
||||
|
||||
## バグ修正
|
||||
|
||||
### WebDAV パスワードの消失
|
||||
|
||||
- 無関係な設定保存時に WebDAV パスワードがサイレントにクリアされる問題を修正
|
||||
|
||||
### ツールメッセージのパース
|
||||
|
||||
- プロキシのツールメッセージパース処理の不具合を修正し、特定のツール呼び出しパターンでのエラーを解消
|
||||
|
||||
### ダークモードの表示
|
||||
|
||||
- ダークモードでの一部 UI コンポーネントの表示不具合を修正
|
||||
|
||||
### Copilot リクエストフィンガープリント
|
||||
|
||||
- Copilot リバースプロキシのリクエストフィンガープリント生成の不具合を修正し、認証エラーを解消
|
||||
|
||||
### プロバイダーフォームの二重送信
|
||||
|
||||
- プロバイダー追加/編集フォームでの高速連続クリックによる重複送信を防止 (#1352、@Hexi1997 に感謝)
|
||||
|
||||
### Ghostty ターミナルセッション復元
|
||||
|
||||
- Ghostty ターミナルでの Claude セッション復元の失敗を修正 (#1506、@canyonsehun に感謝)
|
||||
|
||||
### Skill ZIP インポート拡張子
|
||||
|
||||
- ZIP インポートダイアログが `.skill` ファイル拡張子をサポートするように修正 (#1240, #1455、@yovinchen に感謝)
|
||||
|
||||
### Skill ZIP インストール対象アプリ
|
||||
|
||||
- ZIP 方式でインストールされた skill が常に Claude をデフォルトにするのではなく、現在アクティブなアプリを使用するように修正
|
||||
|
||||
### OpenClaw アクティブカードのハイライト
|
||||
|
||||
- OpenClaw の現在アクティブなプロバイダーカードがハイライト表示されない問題を修正 (#1419、@funnytime75 に感謝)
|
||||
|
||||
### TOC 付きレスポンシブレイアウト
|
||||
|
||||
- TOC タイトルが存在する場合のレスポンシブデザインを改善 (#1491、@West-Pavilion に感謝)
|
||||
|
||||
### Skills インポートダイアログの白い画面
|
||||
|
||||
- ImportSkillsDialog に不足していた TooltipProvider を追加し、ダイアログを開く際のランタイムクラッシュを防止
|
||||
|
||||
### パネル下部の空白エリア
|
||||
|
||||
- すべてのコンテンツパネルのハードコードされた `h-[calc(100vh-8rem)]` を `flex-1 min-h-0` に置き換え、異なるプラットフォーム間のオフセット値の不一致による下部のギャップを解消
|
||||
|
||||
---
|
||||
|
||||
## ドキュメント
|
||||
|
||||
### 料金モデル ID の正規化
|
||||
|
||||
- 中英日三言語のユーザーマニュアルにモデル ID 正規化ルール(プレフィックス除去、サフィックストリミング、`@`→`-` 置換)の説明セクションを追加 (#1591、@makoMakoGo に感謝)
|
||||
|
||||
### macOS 署名済みメッセージの更新
|
||||
|
||||
- README、README_ZH、インストールガイド(EN/ZH/JA)、FAQ ページ(EN/ZH/JA)からすべての `xattr` 回避策と「開発元を確認できません」警告を削除し、「Apple のコード署名と公証済み」メッセージに置換
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ リスクに関する注意事項
|
||||
|
||||
**GitHub Copilot リバースプロキシに関する免責事項**
|
||||
|
||||
本リリースで追加された Copilot リバースプロキシ機能は、リバースエンジニアリングによる非公式 API を通じて GitHub Copilot サービスにアクセスします。この機能を有効にする前に、以下のリスクをご確認ください:
|
||||
|
||||
1. **利用規約違反の可能性**:この機能は [GitHub 利用規約](https://docs.github.com/en/site-policy/acceptable-use-policies/github-acceptable-use-policies)および[追加製品の利用条件](https://docs.github.com/en/site-policy/github-terms/github-terms-for-additional-products-and-features)に違反する可能性があります。これらの規約では、過度な自動一括操作、サービスの無断複製、自動化手段によるサーバーへの過度な負荷が禁止されています。
|
||||
2. **アカウントリスク**:類似ツールの利用者が GitHub から「スクリプト化されたインタラクション、または意図的に異常もしくは過度な使用」を指摘する警告メールを受け取った事例が報告されています。警告後も使用を継続した場合、Copilot へのアクセスが一時的または永久的に停止される可能性があります。
|
||||
3. **将来の利用保証なし**:GitHub は検出メカニズムをいつでも更新する可能性があり、現在利用可能な使用パターンが将来的にフラグ付けされる可能性があります。
|
||||
|
||||
この機能を有効にすることで、ユーザーは**すべてのリスクを自己責任で負う**ものとします。CC Switch は、この機能の使用に起因するアカウント制限、警告、またはサービス停止について一切の責任を負いません。
|
||||
|
||||
---
|
||||
|
||||
## ダウンロードとインストール
|
||||
|
||||
[Releases](https://github.com/farion1231/cc-switch/releases/latest) から適切なバージョンをダウンロードしてください。
|
||||
|
||||
### システム要件
|
||||
|
||||
| システム | 最小バージョン | アーキテクチャ |
|
||||
| -------- | -------------------------------- | ----------------------------------- |
|
||||
| Windows | Windows 10 以降 | x64 |
|
||||
| macOS | macOS 12 (Monterey) 以降 | Intel (x64) / Apple Silicon (arm64) |
|
||||
| Linux | 下表参照 | x64 |
|
||||
|
||||
### Windows
|
||||
|
||||
| ファイル | 説明 |
|
||||
| ------------------------------------------ | ---------------------------------------------------- |
|
||||
| `CC-Switch-v3.12.3-Windows.msi` | **推奨** - MSI インストーラー、自動更新対応 |
|
||||
| `CC-Switch-v3.12.3-Windows-Portable.zip` | ポータブル版、解凍して実行、レジストリ書き込みなし |
|
||||
|
||||
### macOS
|
||||
|
||||
| ファイル | 説明 |
|
||||
| ---------------------------------- | ----------------------------------------------------------------- |
|
||||
| `CC-Switch-v3.12.3-macOS.dmg` | **推奨** - DMG インストーラー、ドラッグ&ドロップでインストール |
|
||||
| `CC-Switch-v3.12.3-macOS.zip` | 解凍して Applications にドラッグ、Universal Binary |
|
||||
| `CC-Switch-v3.12.3-macOS.tar.gz` | Homebrew インストールと自動更新用 |
|
||||
|
||||
> macOS 版は Apple のコード署名と公証済みで、そのままインストールしてご利用いただけます。
|
||||
|
||||
### Homebrew (macOS)
|
||||
|
||||
```bash
|
||||
brew tap farion1231/ccswitch
|
||||
brew install --cask cc-switch
|
||||
```
|
||||
|
||||
更新:
|
||||
|
||||
```bash
|
||||
brew upgrade --cask cc-switch
|
||||
```
|
||||
|
||||
### Linux
|
||||
|
||||
| ディストリビューション | 推奨形式 | インストール方法 |
|
||||
| --------------------------------------- | ----------- | ---------------------------------------------------------------------- |
|
||||
| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb` または `sudo apt install ./CC-Switch-*.deb` |
|
||||
| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm` または `sudo dnf install ./CC-Switch-*.rpm` |
|
||||
| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
|
||||
| Arch Linux / Manjaro | `.AppImage` | 実行権限を追加して直接実行、または AUR を使用 |
|
||||
| その他のディストリビューション / 不明 | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
|
||||
@@ -0,0 +1,296 @@
|
||||
# CC Switch v3.12.3
|
||||
|
||||
> GitHub Copilot 反向代理、macOS 代码签名与公证、Reasoning Effort 映射、Tool Search 环境变量开关、Skill 备份/恢复生命周期
|
||||
|
||||
**[English →](v3.12.3-en.md) | [日本語版 →](v3.12.3-ja.md)**
|
||||
|
||||
---
|
||||
|
||||
## 概览
|
||||
|
||||
CC Switch v3.12.3 新增了 **GitHub Copilot 反向代理** 支持和 **Copilot Auth Center** 认证管理,引入了 **Reasoning Effort 映射** 实现跨供应商推理强度控制,通过 Claude 2.1.76+ 原生 `ENABLE_TOOL_SEARCH` 环境变量实现了 **Tool Search 开关**,新增了 **OpenCode SQLite 后端** 支持,并完成了 **macOS 代码签名与 Apple 公证**。同时引入了完整的 Skill 备份/恢复生命周期,改进了代理对 OpenAI o 系列模型的兼容性和 gzip 压缩支持,优化了 Skills 缓存策略,更新了 Claude 4.6 上下文窗口、MiniMax M2.7 和小米 MiMo 模型预设,并修复了 WebDAV 密码、工具消息解析、暗色模式和 Copilot 请求指纹等方面的问题。
|
||||
|
||||
**发布日期**:2026-03-24
|
||||
|
||||
**更新规模**:36 commits | 107 files changed | +9,124 / -802 lines
|
||||
|
||||
---
|
||||
|
||||
## 重点内容
|
||||
|
||||
- **GitHub Copilot 反向代理**:新增 Copilot 反向代理支持,通过 Copilot Auth Center 管理 GitHub Token 认证,实现 Copilot 模型在 Claude Code 中的无缝使用([⚠️ 风险提示](#️-风险提示))
|
||||
- **macOS 代码签名与公证**:macOS 版本已通过 Apple 代码签名和公证,新增 DMG 安装格式,无需再手动绕过"未知开发者"警告
|
||||
- **Reasoning Effort 映射**:代理层自动映射 — 显式 `output_config.effort` 优先,回退到 `budget_tokens` 阈值(<4000→low, 4000–16000→medium, ≥16000→high),支持 o 系列和 GPT-5+ 模型
|
||||
- **Tool Search 环境变量开关**:利用 Claude 2.1.76+ 原生 `ENABLE_TOOL_SEARCH` 环境变量,在通用配置编辑器中一键启用 Tool Search
|
||||
- **Skill 备份/恢复生命周期**:卸载前自动备份 Skill 文件;新增备份列表、恢复和删除管理
|
||||
- **OpenCode SQLite 后端**:为 OpenCode 新增 SQLite 会话存储(与现有 JSON 后端并存),ID 冲突时 SQLite 优先的双后端扫描
|
||||
- **Codex 1M 上下文窗口开关**:配置编辑器中一键设置 `model_context_window = 1000000`,自动填充 `model_auto_compact_token_limit`
|
||||
- **禁用自动升级开关**:通用配置编辑器中新增 `DISABLE_AUTOUPDATER` 环境变量复选框,防止 Claude Code 自动升级
|
||||
- **代理 Gzip 压缩**:非流式代理请求自动协商 gzip 压缩,减少带宽消耗
|
||||
- **o 系列模型兼容性**:Chat Completions 代理正确使用 `max_completion_tokens` 处理 o1/o3/o4-mini 模型
|
||||
- **Skills 导入重构**:将基于文件系统的隐式应用推断替换为显式的 `ImportSkillSelection`,防止多应用错误激活
|
||||
|
||||
---
|
||||
|
||||
## 新功能
|
||||
|
||||
### GitHub Copilot 反向代理
|
||||
|
||||
新增完整的 GitHub Copilot 集成,作为 Claude Code 供应商使用。
|
||||
|
||||
- 通过 OAuth Device Code 流程进行 GitHub 认证
|
||||
- 支持多账号管理和自动 Token 刷新
|
||||
- Anthropic ↔ OpenAI 格式自动转换
|
||||
- 实时获取可用模型列表和用量统计 (#930,感谢 @Mason-mengze)
|
||||
|
||||
### Copilot Auth Center
|
||||
|
||||
在设置中新增认证中心面板,全局管理 GitHub 账号。
|
||||
|
||||
- 支持按供应商绑定账号(通过 `meta.authBinding`)
|
||||
- 统一的 Token 管理和刷新机制
|
||||
|
||||
### Tool Search 开关
|
||||
|
||||
利用 Claude 2.1.76+ 原生 `ENABLE_TOOL_SEARCH` 环境变量控制 Tool Search 功能。
|
||||
|
||||
- 在供应商通用配置编辑器中以复选框形式暴露
|
||||
- 替代了之前的二进制补丁方案,更简洁可靠 (#930,感谢 @Mason-mengze)
|
||||
|
||||
### Reasoning Effort 映射
|
||||
|
||||
新增代理层自动推理强度映射,支持 OpenAI o 系列和 GPT-5+ 模型。
|
||||
|
||||
- 两级解析:显式 `output_config.effort` 优先,回退到 `budget_tokens` 阈值(<4000→low, 4000–16000→medium, ≥16000→high)
|
||||
- 覆盖 Chat Completions 和 Responses API 两条路径,含 17 个单元测试
|
||||
|
||||
### OpenCode SQLite 后端
|
||||
|
||||
为 OpenCode 新增 SQLite 会话存储支持(与现有 JSON 后端并存)。
|
||||
|
||||
- 双后端扫描,ID 冲突时 SQLite 优先
|
||||
- 原子会话删除和路径校验
|
||||
- JSON 后端保持向后兼容
|
||||
|
||||
### Codex 1M 上下文窗口开关
|
||||
|
||||
在配置编辑器中新增 Codex 1M 上下文窗口一键开关。
|
||||
|
||||
- 复选框设置 `config.toml` 中的 `model_context_window = 1000000`
|
||||
- 启用时自动填充 `model_auto_compact_token_limit = 900000`
|
||||
- 关闭时干净移除两个字段
|
||||
|
||||
### 禁用自动升级开关
|
||||
|
||||
在 Claude 通用配置编辑器中新增禁用自动升级的复选框。
|
||||
|
||||
- 勾选后设置 `DISABLE_AUTOUPDATER=1` 环境变量,阻止 Claude Code 自动升级
|
||||
- 与 Teammates 模式、Tool Search、高强度思考等开关同一排显示
|
||||
|
||||
### Skill 卸载自动备份
|
||||
|
||||
卸载 Skill 前自动备份文件,防止数据意外丢失。
|
||||
|
||||
- 备份存储在 `~/.cc-switch/skill-backups/`,包含所有 skill 文件和记录原始元数据的 `meta.json`
|
||||
- 旧备份自动清理,最多保留 20 个
|
||||
- 备份路径返回前端并在成功提示中显示
|
||||
|
||||
### Skill 备份恢复与删除
|
||||
|
||||
新增卸载时创建的 Skill 备份的管理功能。
|
||||
|
||||
- 列出所有可用的 skill 备份及元数据
|
||||
- 恢复操作将文件拷回 SSOT,保存数据库记录,并同步到当前应用,失败时自动回滚
|
||||
- 删除操作在确认对话框后移除备份目录
|
||||
|
||||
### macOS 代码签名与 Apple 公证
|
||||
|
||||
CI 流程新增完整的 macOS 代码签名和 Apple 公证支持。
|
||||
|
||||
- 导入 Apple Developer ID 证书,签名 Universal Binary
|
||||
- 提交 Apple 公证并将票据装订到 `.app` 和 `.dmg`
|
||||
- 硬性验证步骤(`codesign --verify` + `spctl -a` + `stapler validate`)把关发布
|
||||
|
||||
---
|
||||
|
||||
## 变更
|
||||
|
||||
### Skills 缓存策略优化
|
||||
|
||||
- 将 `invalidateQueries` 替换为直接 `setQueryData` 更新,用于 skill 安装/卸载/导入操作
|
||||
- 新增 `staleTime: Infinity` 和 `keepPreviousData`,消除加载闪烁 (#1573,感谢 @TangZhiZzz)
|
||||
|
||||
### 代理 Gzip 压缩
|
||||
|
||||
- 非流式请求允许 reqwest 自动协商 gzip 并透明解压响应
|
||||
- 流式请求保守地保持 `Accept-Encoding: identity`,避免中断的 SSE 流解压出错
|
||||
|
||||
### o1/o3 模型兼容性
|
||||
|
||||
- Chat Completions 路径对 o1/o3/o4-mini 模型使用 `max_completion_tokens` 替代 `max_tokens` (#1451,感谢 @Hemilt0n)
|
||||
- Responses API 路径保持使用正确的 `max_output_tokens` 字段
|
||||
|
||||
### OpenCode 模型变体
|
||||
|
||||
- 将 OpenCode 的模型变体放在预设顶层而非嵌套在 options 内部,提升可发现性 (#1317)
|
||||
|
||||
### Skills 导入流程
|
||||
|
||||
- 将基于文件系统的隐式应用推断替换为显式的 `ImportSkillSelection`,防止同一 skill 目录存在于多个应用路径下时错误激活多个应用
|
||||
- 为 `sync_to_app` 增加协调逻辑,移除已禁用/孤立的符号链接
|
||||
- MCP `sync_all_enabled` 现在会从 live 配置中移除已禁用的服务器
|
||||
|
||||
### Claude 4.6 上下文窗口
|
||||
|
||||
- Claude Opus 4.6 和 Sonnet 4.6 上下文窗口从 200K 更新至 1M(GA 发布)
|
||||
|
||||
### MiniMax 模型升级
|
||||
|
||||
- MiniMax 预设从 M2.5 升级至 M2.7,更新三语合作伙伴描述
|
||||
|
||||
### 小米 MiMo 模型升级
|
||||
|
||||
- MiMo 预设从 mimo-v2-flash 升级至 mimo-v2-pro
|
||||
|
||||
### 添加供应商对话框简化
|
||||
|
||||
- 移除冗余的 OAuth 标签页,对话框从 3 个标签页减少到 2 个(应用专属 + 通用)
|
||||
|
||||
### 供应商表单高级选项折叠
|
||||
|
||||
- Claude 供应商表单中的模型映射、API 格式等高级字段在未填写时默认折叠
|
||||
- 预设填充值后自动展开,手动清空不会自动折叠
|
||||
|
||||
---
|
||||
|
||||
## Bug 修复
|
||||
|
||||
### WebDAV 密码被静默清除
|
||||
|
||||
- 修复 ProviderList 或 UsageScriptModal 保存设置时 WebDAV 密码被静默清除的问题
|
||||
- 前端 payload 中剥离 `webdavSync`,后端 `merge_settings_for_save()` 增加回填逻辑保护现有密码
|
||||
|
||||
### 工具消息解析
|
||||
|
||||
- 修复 Claude(tool_result content blocks)、Codex(function_call/function_call_output payloads)和 Gemini(array content + toolCalls extraction)的 tool_use/tool_result 消息分类 (#1401,感谢 @BlueOcean223)
|
||||
|
||||
### 暗色模式选择器
|
||||
|
||||
- 将 Tailwind `darkMode` 从 `["selector", "class"]` 改为 `["selector", ".dark"]`,确保暗色模式正确激活 (#1596,感谢 @qinxiandiqi)
|
||||
|
||||
### Copilot 请求指纹
|
||||
|
||||
- 统一所有 Copilot API 调用点的请求指纹头,防止 User-Agent 泄漏和 Stream Check 不匹配
|
||||
|
||||
### 供应商表单防重复提交
|
||||
|
||||
- 修复快速连续点击按钮时供应商添加/编辑表单重复提交的问题 (#1352,感谢 @Hexi1997)
|
||||
|
||||
### Ghostty 终端会话恢复
|
||||
|
||||
- 修复在 Ghostty 终端中恢复 Claude 会话失败的问题 (#1506,感谢 @canyonsehun)
|
||||
|
||||
### Skill ZIP 导入扩展名
|
||||
|
||||
- ZIP 导入对话框现在支持 `.skill` 文件扩展名 (#1240, #1455,感谢 @yovinchen)
|
||||
|
||||
### Skill ZIP 安装目标应用
|
||||
|
||||
- ZIP 方式安装的 skill 现在使用当前活跃应用,而非始终默认为 Claude
|
||||
|
||||
### OpenClaw 活跃供应商高亮
|
||||
|
||||
- 修复 OpenClaw 当前激活的供应商卡片未高亮显示的问题 (#1419,感谢 @funnytime75)
|
||||
|
||||
### 响应式布局与 TOC
|
||||
|
||||
- 改善存在 TOC 标题时的响应式布局 (#1491,感谢 @West-Pavilion)
|
||||
|
||||
### Skills 导入对话框白屏
|
||||
|
||||
- 在 ImportSkillsDialog 中补充缺失的 TooltipProvider,修复打开对话框时的运行时崩溃
|
||||
|
||||
### 面板底部空白区域
|
||||
|
||||
- 将所有内容面板的硬编码 `h-[calc(100vh-8rem)]` 替换为 `flex-1 min-h-0`,消除因不同平台偏移量不匹配导致的底部空白
|
||||
|
||||
---
|
||||
|
||||
## 文档
|
||||
|
||||
### 定价模型 ID 归一化
|
||||
|
||||
- 在中英日三语用户手册中新增模型 ID 归一化规则说明(前缀剥离、后缀修剪、`@`→`-` 替换)(#1591,感谢 @makoMakoGo)
|
||||
|
||||
### macOS 签名与公证说明
|
||||
|
||||
- 移除 README、安装指南和 FAQ 中所有 `xattr` 变通方案和"未知开发者"警告
|
||||
- 替换为"已通过 Apple 代码签名和公证"的说明
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ 风险提示
|
||||
|
||||
**GitHub Copilot 反向代理免责声明**
|
||||
|
||||
本版本新增的 Copilot 反向代理功能通过逆向工程的非官方 API 访问 GitHub Copilot 服务。启用此功能前,请注意以下风险:
|
||||
|
||||
1. **违反服务条款**:此功能可能违反 [GitHub 可接受使用政策](https://docs.github.com/en/site-policy/acceptable-use-policies/github-acceptable-use-policies)和[附加产品条款](https://docs.github.com/en/site-policy/github-terms/github-terms-for-additional-products-and-features),其中禁止过度自动化批量活动、未经授权的服务复制以及通过自动化手段对服务器施加不当负担。
|
||||
2. **账号风险**:已有类似工具的用户收到 GitHub 官方警告邮件,指出其存在"脚本化交互或其他刻意的异常或高强度使用"行为。收到警告后继续使用可能导致 Copilot 访问权限被暂停甚至永久封禁。
|
||||
3. **无法保证长期可用**:GitHub 可能随时更新其检测机制,当前可用的使用方式未来可能被标记。
|
||||
|
||||
用户启用此功能即表示**自行承担所有风险**。CC Switch 不对因使用此功能而导致的任何账号限制、警告或服务暂停承担责任。
|
||||
|
||||
---
|
||||
|
||||
## 下载与安装
|
||||
|
||||
访问 [Releases](https://github.com/farion1231/cc-switch/releases/latest) 下载对应版本。
|
||||
|
||||
### 系统要求
|
||||
|
||||
| 系统 | 最低版本 | 架构 |
|
||||
| ------- | ----------------------------- | ----------------------------------- |
|
||||
| Windows | Windows 10 及以上 | x64 |
|
||||
| macOS | macOS 12 (Monterey) 及以上 | Intel (x64) / Apple Silicon (arm64) |
|
||||
| Linux | 见下表 | x64 |
|
||||
|
||||
### Windows
|
||||
|
||||
| 文件 | 说明 |
|
||||
| ------------------------------------------ | ----------------------------------- |
|
||||
| `CC-Switch-v3.12.3-Windows.msi` | **推荐** - MSI 安装包,支持自动更新 |
|
||||
| `CC-Switch-v3.12.3-Windows-Portable.zip` | 便携版,解压即用,不写入注册表 |
|
||||
|
||||
### macOS
|
||||
|
||||
| 文件 | 说明 |
|
||||
| ---------------------------------- | --------------------------------------------------------- |
|
||||
| `CC-Switch-v3.12.3-macOS.dmg` | **推荐** - DMG 安装包,拖入 Applications 即可 |
|
||||
| `CC-Switch-v3.12.3-macOS.zip` | 解压后拖入 Applications,Universal Binary |
|
||||
| `CC-Switch-v3.12.3-macOS.tar.gz` | 用于 Homebrew 安装和自动更新 |
|
||||
|
||||
> macOS 版本已通过 Apple 代码签名和公证,可直接安装使用。
|
||||
|
||||
### Homebrew(macOS)
|
||||
|
||||
```bash
|
||||
brew tap farion1231/ccswitch
|
||||
brew install --cask cc-switch
|
||||
```
|
||||
|
||||
更新:
|
||||
|
||||
```bash
|
||||
brew upgrade --cask cc-switch
|
||||
```
|
||||
|
||||
### Linux
|
||||
|
||||
| 发行版 | 推荐格式 | 安装方式 |
|
||||
| --------------------------------------- | ----------- | ---------------------------------------------------------------------- |
|
||||
| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb` 或 `sudo apt install ./CC-Switch-*.deb` |
|
||||
| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm` 或 `sudo dnf install ./CC-Switch-*.rpm` |
|
||||
| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
|
||||
| Arch Linux / Manjaro | `.AppImage` | 添加执行权限后直接运行,或使用 AUR |
|
||||
| 其他发行版 / 不确定 | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
|
||||
@@ -131,21 +131,9 @@ brew upgrade --cask cc-switch
|
||||
2. Extract to get `CC Switch.app`
|
||||
3. Drag it to the Applications folder
|
||||
|
||||
### First Launch Warning
|
||||
### Signed and Notarized
|
||||
|
||||
Since the developer does not have an Apple Developer account, a "developer cannot be verified" warning may appear on first launch:
|
||||
|
||||
**Recommended solution**:
|
||||
Open Terminal and run the following command:
|
||||
```bash
|
||||
sudo xattr -dr com.apple.quarantine /Applications/CC\ Switch.app/
|
||||
```
|
||||
|
||||
**Alternative solution (via System Settings)**:
|
||||
1. Close the warning dialog
|
||||
2. Open "System Settings" > "Privacy & Security"
|
||||
3. Find the CC Switch prompt and click "Open Anyway"
|
||||
4. Reopen the app to use it normally
|
||||
CC Switch for macOS is signed and notarized by Apple. You can install and open it directly — no extra steps needed.
|
||||
|
||||
## Linux
|
||||
|
||||
|
||||
@@ -186,6 +186,22 @@ Set prices for each model (per million tokens):
|
||||
| Cache Read Price | Price per million cache hit tokens |
|
||||
| Cache Creation Price | Price per million cache creation tokens |
|
||||
|
||||
### Model ID Normalization Rules
|
||||
|
||||
Before matching pricing, CC Switch normalizes the requested model ID:
|
||||
|
||||
- Remove everything before the last `/`
|
||||
- Remove everything after `:`
|
||||
- Replace `@` with `-`
|
||||
|
||||
When adding pricing entries, enter the normalized Model ID rather than the full raw model name from the request.
|
||||
|
||||
| Raw model name | Model ID to enter | Note |
|
||||
|-------|-------------------|------|
|
||||
| `stepfun-ai/step-3.5-flash` | `step-3.5-flash` | Removes the provider prefix |
|
||||
| `moonshotai/kimi-k2-0905:exa` | `kimi-k2-0905` | Removes the prefix and the `:` suffix |
|
||||
| `gpt-5.2-codex@low` | `gpt-5.2-codex-low` | Replaces `@` with `-` |
|
||||
|
||||
### Operations
|
||||
|
||||
- **Add**: Click the "Add" button to add model pricing
|
||||
|
||||
@@ -2,23 +2,9 @@
|
||||
|
||||
## Installation Issues
|
||||
|
||||
### macOS Shows "Unidentified Developer"
|
||||
### macOS Installation
|
||||
|
||||
**Problem**: First launch shows "Cannot open because it is from an unidentified developer"
|
||||
|
||||
**Solution 1**: Via System Settings
|
||||
1. Close the warning dialog
|
||||
2. Open "System Settings" > "Privacy & Security"
|
||||
3. Find the CC Switch prompt
|
||||
4. Click "Open Anyway"
|
||||
5. Reopen the app
|
||||
|
||||
**Solution 2**: Via Terminal command (recommended)
|
||||
```bash
|
||||
sudo xattr -dr com.apple.quarantine /Applications/CC\ Switch.app/
|
||||
```
|
||||
|
||||
The app can be opened normally after running this command.
|
||||
CC Switch for macOS is code-signed and notarized by Apple. You can download and install it directly without any additional steps. If you encounter issues, try downloading the latest version from the [Releases page](https://github.com/farion1231/cc-switch/releases).
|
||||
|
||||
### Windows: App Doesn't Launch After Installation
|
||||
|
||||
|
||||
@@ -131,21 +131,9 @@ brew upgrade --cask cc-switch
|
||||
2. 展開して `CC Switch.app` を取得
|
||||
3. 「アプリケーション」フォルダにドラッグ
|
||||
|
||||
### 初回起動時の警告
|
||||
### 署名・公証済み
|
||||
|
||||
開発者が Apple 開発者アカウントを持っていないため、初回起動時に「不明な開発者」の警告が表示される場合があります:
|
||||
|
||||
**推奨される解決方法**:
|
||||
ターミナルで以下のコマンドを実行してください:
|
||||
```bash
|
||||
sudo xattr -dr com.apple.quarantine /Applications/CC\ Switch.app/
|
||||
```
|
||||
|
||||
**別の解決方法(システム設定から)**:
|
||||
1. 警告ダイアログを閉じる
|
||||
2. 「システム設定」→「プライバシーとセキュリティ」を開く
|
||||
3. CC Switch に関する表示を見つけ、「このまま開く」をクリック
|
||||
4. 再度アプリを開くと正常に使用可能
|
||||
CC Switch の macOS 版は Apple のコード署名と公証を受けています。追加の操作なしで直接インストールして開くことができます。
|
||||
|
||||
## Linux
|
||||
|
||||
|
||||
@@ -186,6 +186,22 @@ Token 使用量の変化を表示:
|
||||
| キャッシュ読取価格 | 100 万キャッシュヒット Token あたりの価格 |
|
||||
| キャッシュ作成価格 | 100 万キャッシュ作成 Token あたりの価格 |
|
||||
|
||||
### モデル ID の正規化ルール
|
||||
|
||||
料金を照合する前に、CC Switch はリクエスト内のモデル ID を正規化します:
|
||||
|
||||
- 最後の `/` より前の接頭辞を削除
|
||||
- `:` 以降の接尾辞を削除
|
||||
- `@` を `-` に置換
|
||||
|
||||
料金設定では、リクエスト内の完全な元のモデル名ではなく、正規化後のモデル ID を入力してください。
|
||||
|
||||
| 元のモデル名 | 入力するモデル ID | 説明 |
|
||||
|------|------|------|
|
||||
| `stepfun-ai/step-3.5-flash` | `step-3.5-flash` | プロバイダー接頭辞を削除 |
|
||||
| `moonshotai/kimi-k2-0905:exa` | `kimi-k2-0905` | 接頭辞と `:` 以降を削除 |
|
||||
| `gpt-5.2-codex@low` | `gpt-5.2-codex-low` | `@` を `-` に置換 |
|
||||
|
||||
### 操作
|
||||
|
||||
- **追加**:「追加」ボタンで新しいモデル価格を追加
|
||||
|
||||
@@ -2,23 +2,9 @@
|
||||
|
||||
## インストールに関する問題
|
||||
|
||||
### macOS で「不明な開発者」と表示される
|
||||
### macOS のインストール
|
||||
|
||||
**問題**:初回起動時に「開けません。身元不明の開発者のものです」と表示される
|
||||
|
||||
**解決方法 1**:システム設定から
|
||||
1. 警告ダイアログを閉じる
|
||||
2. 「システム設定」→「プライバシーとセキュリティ」を開く
|
||||
3. CC Switch に関する表示を見つける
|
||||
4. 「このまま開く」をクリック
|
||||
5. 再度アプリを開く
|
||||
|
||||
**解決方法 2**:ターミナルコマンドから(推奨)
|
||||
```bash
|
||||
sudo xattr -dr com.apple.quarantine /Applications/CC\ Switch.app/
|
||||
```
|
||||
|
||||
実行後、正常にアプリを開けるようになります。
|
||||
CC Switch の macOS 版は Apple のコード署名と公証を受けています。追加の操作なしで直接ダウンロードしてインストールできます。問題が発生した場合は、[Releases ページ](https://github.com/farion1231/cc-switch/releases) から最新版をダウンロードしてください。
|
||||
|
||||
### Windows でインストール後に起動できない
|
||||
|
||||
|
||||
@@ -145,21 +145,9 @@ brew upgrade --cask cc-switch
|
||||
2. 解压得到 `CC Switch.app`
|
||||
3. 拖动到「应用程序」文件夹
|
||||
|
||||
### 首次打开提示
|
||||
### 已签名并公证
|
||||
|
||||
由于开发者没有 Apple 开发者账号,首次打开可能出现「未知开发者」警告:
|
||||
|
||||
**推荐解决方法**:
|
||||
打开终端执行以下命令:
|
||||
```bash
|
||||
sudo xattr -dr com.apple.quarantine /Applications/CC\ Switch.app/
|
||||
```
|
||||
|
||||
**备选解决方法(通过系统设置)**:
|
||||
1. 关闭警告弹窗
|
||||
2. 打开「系统设置」→「隐私与安全性」
|
||||
3. 找到 CC Switch 相关提示,点击「仍要打开」
|
||||
4. 再次打开应用即可正常使用
|
||||
CC Switch macOS 版本已通过 Apple 代码签名和公证,可直接安装打开,无需额外操作。
|
||||
|
||||
## Linux
|
||||
|
||||
|
||||
@@ -186,6 +186,22 @@
|
||||
| 缓存读取价格 | 每百万缓存命中 Token 的价格 |
|
||||
| 缓存创建价格 | 每百万缓存创建 Token 的价格 |
|
||||
|
||||
### 模型 ID 匹配规则
|
||||
|
||||
在匹配定价前,CC Switch 会先对请求中的模型 ID 做标准化处理:
|
||||
|
||||
- 去掉最后一个 `/` 之前的前缀
|
||||
- 去掉 `:` 之后的后缀
|
||||
- 将 `@` 替换为 `-`
|
||||
|
||||
因此,在定价配置中请填写清洗后的模型 ID,而不是请求里的完整原始模型名。
|
||||
|
||||
| 原始模型名 | 应填写的模型 ID | 说明 |
|
||||
|------|------|------|
|
||||
| `stepfun-ai/step-3.5-flash` | `step-3.5-flash` | 去掉供应商前缀 |
|
||||
| `moonshotai/kimi-k2-0905:exa` | `kimi-k2-0905` | 去掉前缀和 `:` 后缀 |
|
||||
| `gpt-5.2-codex@low` | `gpt-5.2-codex-low` | 将 `@` 替换为 `-` |
|
||||
|
||||
### 操作
|
||||
|
||||
- **添加**:点击「添加」按钮新增模型定价
|
||||
|
||||
@@ -2,23 +2,9 @@
|
||||
|
||||
## 安装问题
|
||||
|
||||
### macOS 提示「未知开发者」
|
||||
### macOS 安装
|
||||
|
||||
**问题**:首次打开时提示「无法打开,因为它来自身份不明的开发者」
|
||||
|
||||
**解决方法一**:通过系统设置
|
||||
1. 关闭警告弹窗
|
||||
2. 打开「系统设置」→「隐私与安全性」
|
||||
3. 找到 CC Switch 相关提示
|
||||
4. 点击「仍要打开」
|
||||
5. 再次打开应用
|
||||
|
||||
**解决方法二**:通过终端命令(推荐)
|
||||
```bash
|
||||
sudo xattr -dr com.apple.quarantine /Applications/CC\ Switch.app/
|
||||
```
|
||||
|
||||
执行后即可正常打开应用。
|
||||
CC Switch macOS 版本已通过 Apple 代码签名和公证,可直接下载安装,无需额外操作。如遇问题,请尝试从 [Releases 页面](https://github.com/farion1231/cc-switch/releases) 下载最新版本。
|
||||
|
||||
### Windows 安装后无法启动
|
||||
|
||||
|
||||
+2
-3
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cc-switch",
|
||||
"version": "3.12.1",
|
||||
"version": "3.12.3",
|
||||
"description": "All-in-One Assistant for Claude Code, Codex & Gemini CLI",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
@@ -90,6 +90,5 @@
|
||||
"sonner": "^2.0.7",
|
||||
"tailwind-merge": "^3.3.1",
|
||||
"zod": "^4.1.12"
|
||||
},
|
||||
"packageManager": "pnpm@10.10.0+sha512.d615db246fe70f25dcfea6d8d73dee782ce23e2245e3c4f6f888249fb568149318637dca73c2c5c8ef2a4ca0d5657fb9567188bfab47f566d1ee6ce987815c39"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,3 +4,4 @@ module.exports = {
|
||||
autoprefixer: {},
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
Generated
+91
-6
@@ -312,6 +312,28 @@ version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
|
||||
|
||||
[[package]]
|
||||
name = "aws-lc-rs"
|
||||
version = "1.15.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e84ce723ab67259cfeb9877c6a639ee9eb7a27b28123abd71db7f0d5d0cc9d86"
|
||||
dependencies = [
|
||||
"aws-lc-sys",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aws-lc-sys"
|
||||
version = "0.36.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "43a442ece363113bd4bd4c8b18977a7798dd4d3c3383f34fb61936960e8f4ad8"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"cmake",
|
||||
"dunce",
|
||||
"fs_extra",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "axum"
|
||||
version = "0.7.9"
|
||||
@@ -484,6 +506,17 @@ dependencies = [
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "brotli"
|
||||
version = "7.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc97b8f16f944bba54f0433f07e30be199b6dc2bd25937444bbad560bcea29bd"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
"alloc-stdlib",
|
||||
"brotli-decompressor 4.0.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "brotli"
|
||||
version = "8.0.2"
|
||||
@@ -492,7 +525,17 @@ checksum = "4bd8b9603c7aa97359dbd97ecf258968c95f3adddd6db2f7e7a5bef101c84560"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
"alloc-stdlib",
|
||||
"brotli-decompressor",
|
||||
"brotli-decompressor 5.0.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "brotli-decompressor"
|
||||
version = "4.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a334ef7c9e23abf0ce748e8cd309037da93e606ad52eb372e4ce327a0dcfbdfd"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
"alloc-stdlib",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -672,18 +715,26 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cc-switch"
|
||||
version = "3.12.1"
|
||||
version = "3.12.3"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-stream",
|
||||
"auto-launch",
|
||||
"axum",
|
||||
"base64 0.22.1",
|
||||
"brotli 7.0.0",
|
||||
"bytes",
|
||||
"chrono",
|
||||
"dirs 5.0.1",
|
||||
"flate2",
|
||||
"futures",
|
||||
"http",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"httparse",
|
||||
"hyper",
|
||||
"hyper-rustls",
|
||||
"hyper-util",
|
||||
"indexmap 2.13.0",
|
||||
"json-five",
|
||||
"json5",
|
||||
@@ -696,6 +747,8 @@ dependencies = [
|
||||
"rquickjs",
|
||||
"rusqlite",
|
||||
"rust_decimal",
|
||||
"rustls",
|
||||
"rustls-native-certs",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_yaml",
|
||||
@@ -714,6 +767,7 @@ dependencies = [
|
||||
"tempfile",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"toml 0.8.23",
|
||||
"toml_edit 0.22.27",
|
||||
"tower 0.4.13",
|
||||
@@ -721,6 +775,7 @@ dependencies = [
|
||||
"url",
|
||||
"uuid",
|
||||
"webkit2gtk",
|
||||
"webpki-roots 0.26.11",
|
||||
"winreg 0.52.0",
|
||||
"zip 2.4.2",
|
||||
]
|
||||
@@ -788,6 +843,15 @@ dependencies = [
|
||||
"inout",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cmake"
|
||||
version = "0.1.57"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "75443c44cd6b379beb8c5b45d85d0773baf31cce901fe7bb252f4eff3008ef7d"
|
||||
dependencies = [
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "combine"
|
||||
version = "4.6.7"
|
||||
@@ -1544,6 +1608,12 @@ dependencies = [
|
||||
"percent-encoding",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fs_extra"
|
||||
version = "1.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"
|
||||
|
||||
[[package]]
|
||||
name = "funty"
|
||||
version = "2.0.0"
|
||||
@@ -2177,12 +2247,14 @@ dependencies = [
|
||||
"http",
|
||||
"hyper",
|
||||
"hyper-util",
|
||||
"log",
|
||||
"rustls",
|
||||
"rustls-native-certs",
|
||||
"rustls-pki-types",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tower-service",
|
||||
"webpki-roots",
|
||||
"webpki-roots 1.0.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4171,7 +4243,7 @@ dependencies = [
|
||||
"wasm-bindgen-futures",
|
||||
"wasm-streams 0.4.2",
|
||||
"web-sys",
|
||||
"webpki-roots",
|
||||
"webpki-roots 1.0.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4381,6 +4453,8 @@ version = "0.23.37"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "758025cb5fccfd3bc2fd74708fd4682be41d99e5dff73c377c0646c6012c73a4"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"log",
|
||||
"once_cell",
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
@@ -4444,6 +4518,7 @@ version = "0.103.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d7df23109aa6c1567d1c575b9952556388da57401e4ace1d15f79eedad0d8f53"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
"untrusted",
|
||||
@@ -4686,6 +4761,7 @@ version = "1.0.149"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
|
||||
dependencies = [
|
||||
"indexmap 2.13.0",
|
||||
"itoa",
|
||||
"memchr",
|
||||
"serde",
|
||||
@@ -5296,7 +5372,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d4a24476afd977c5d5d169f72425868613d82747916dd29e0a357c84c4bd6d29"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"brotli",
|
||||
"brotli 8.0.2",
|
||||
"ico",
|
||||
"json-patch",
|
||||
"plist",
|
||||
@@ -5584,7 +5660,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "219a1f983a2af3653f75b5747f76733b0da7ff03069c7a41901a5eb3ace4557d"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"brotli",
|
||||
"brotli 8.0.2",
|
||||
"cargo_metadata",
|
||||
"ctor",
|
||||
"dunce",
|
||||
@@ -6530,6 +6606,15 @@ dependencies = [
|
||||
"rustls-pki-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webpki-roots"
|
||||
version = "0.26.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
|
||||
dependencies = [
|
||||
"webpki-roots 1.0.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webpki-roots"
|
||||
version = "1.0.6"
|
||||
|
||||
+14
-2
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "cc-switch"
|
||||
version = "3.12.1"
|
||||
version = "3.12.3"
|
||||
description = "All-in-One Assistant for Claude Code, Codex & Gemini CLI"
|
||||
authors = ["Jason Young"]
|
||||
license = "MIT"
|
||||
@@ -23,7 +23,7 @@ test-hooks = []
|
||||
tauri-build = { version = "2.4.0", features = [] }
|
||||
|
||||
[dependencies]
|
||||
serde_json = "1.0"
|
||||
serde_json = { version = "1.0", features = ["preserve_order"] }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
log = "0.4"
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
@@ -39,6 +39,8 @@ dirs = "5.0"
|
||||
toml = "0.8"
|
||||
toml_edit = "0.22"
|
||||
reqwest = { version = "0.12", features = ["rustls-tls", "json", "stream", "socks"] }
|
||||
flate2 = "1"
|
||||
brotli = "7"
|
||||
tokio = { version = "1", features = ["macros", "rt-multi-thread", "time", "sync"] }
|
||||
futures = "0.3"
|
||||
async-stream = "0.3"
|
||||
@@ -47,6 +49,16 @@ axum = "0.7"
|
||||
tower = "0.4"
|
||||
tower-http = { version = "0.5", features = ["cors"] }
|
||||
hyper = { version = "1.0", features = ["full"] }
|
||||
hyper-util = { version = "0.1", features = ["tokio", "http1", "client-legacy"] }
|
||||
hyper-rustls = { version = "0.27", features = ["http1", "tls12", "ring", "webpki-tokio"] }
|
||||
http = "1"
|
||||
http-body = "1"
|
||||
http-body-util = "0.1"
|
||||
httparse = "1"
|
||||
tokio-rustls = "0.26"
|
||||
rustls = "0.23"
|
||||
webpki-roots = "0.26"
|
||||
rustls-native-certs = "0.8"
|
||||
regex = "1.10"
|
||||
rquickjs = { version = "0.8", features = ["array-buffer", "classes"] }
|
||||
thiserror = "2.0"
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 9.1 KiB |
@@ -883,6 +883,7 @@ mod tests {
|
||||
dir: TempDir,
|
||||
original_home: Option<String>,
|
||||
original_userprofile: Option<String>,
|
||||
original_test_home: Option<String>,
|
||||
}
|
||||
|
||||
impl TempHome {
|
||||
@@ -890,14 +891,17 @@ mod tests {
|
||||
let dir = TempDir::new().expect("failed to create temp home");
|
||||
let original_home = env::var("HOME").ok();
|
||||
let original_userprofile = env::var("USERPROFILE").ok();
|
||||
let original_test_home = env::var("CC_SWITCH_TEST_HOME").ok();
|
||||
|
||||
env::set_var("HOME", dir.path());
|
||||
env::set_var("USERPROFILE", dir.path());
|
||||
env::set_var("CC_SWITCH_TEST_HOME", dir.path());
|
||||
|
||||
Self {
|
||||
dir,
|
||||
original_home,
|
||||
original_userprofile,
|
||||
original_test_home,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -913,6 +917,11 @@ mod tests {
|
||||
Some(value) => env::set_var("USERPROFILE", value),
|
||||
None => env::remove_var("USERPROFILE"),
|
||||
}
|
||||
|
||||
match &self.original_test_home {
|
||||
Some(value) => env::set_var("CC_SWITCH_TEST_HOME", value),
|
||||
None => env::remove_var("CC_SWITCH_TEST_HOME"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ use crate::error::AppError;
|
||||
use serde_json::Value;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use toml_edit::DocumentMut;
|
||||
|
||||
/// 获取 Codex 配置目录路径
|
||||
pub fn get_codex_config_dir() -> PathBuf {
|
||||
@@ -135,3 +136,335 @@ pub fn read_and_validate_codex_config_text() -> Result<String, AppError> {
|
||||
validate_config_toml(&s)?;
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
/// Update a field in Codex config.toml using toml_edit (syntax-preserving).
|
||||
///
|
||||
/// Supported fields:
|
||||
/// - `"base_url"`: writes to `[model_providers.<current>].base_url` if `model_provider` exists,
|
||||
/// otherwise falls back to top-level `base_url`.
|
||||
/// - `"model"`: writes to top-level `model` field.
|
||||
///
|
||||
/// Empty value removes the field.
|
||||
pub fn update_codex_toml_field(toml_str: &str, field: &str, value: &str) -> Result<String, String> {
|
||||
let mut doc = toml_str
|
||||
.parse::<DocumentMut>()
|
||||
.map_err(|e| format!("TOML parse error: {e}"))?;
|
||||
|
||||
let trimmed = value.trim();
|
||||
|
||||
match field {
|
||||
"base_url" => {
|
||||
let model_provider = doc
|
||||
.get("model_provider")
|
||||
.and_then(|item| item.as_str())
|
||||
.map(str::to_string);
|
||||
|
||||
if let Some(provider_key) = model_provider {
|
||||
// Ensure [model_providers] table exists
|
||||
if doc.get("model_providers").is_none() {
|
||||
doc["model_providers"] = toml_edit::table();
|
||||
}
|
||||
|
||||
if let Some(model_providers) = doc["model_providers"].as_table_mut() {
|
||||
// Ensure [model_providers.<provider_key>] table exists
|
||||
if !model_providers.contains_key(&provider_key) {
|
||||
model_providers[&provider_key] = toml_edit::table();
|
||||
}
|
||||
|
||||
if let Some(provider_table) = model_providers[&provider_key].as_table_mut() {
|
||||
if trimmed.is_empty() {
|
||||
provider_table.remove("base_url");
|
||||
} else {
|
||||
provider_table["base_url"] = toml_edit::value(trimmed);
|
||||
}
|
||||
return Ok(doc.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: no model_provider or structure mismatch → top-level base_url
|
||||
if trimmed.is_empty() {
|
||||
doc.as_table_mut().remove("base_url");
|
||||
} else {
|
||||
doc["base_url"] = toml_edit::value(trimmed);
|
||||
}
|
||||
}
|
||||
"model" => {
|
||||
if trimmed.is_empty() {
|
||||
doc.as_table_mut().remove("model");
|
||||
} else {
|
||||
doc["model"] = toml_edit::value(trimmed);
|
||||
}
|
||||
}
|
||||
_ => return Err(format!("unsupported field: {field}")),
|
||||
}
|
||||
|
||||
Ok(doc.to_string())
|
||||
}
|
||||
|
||||
/// Remove `base_url` from the active model_provider section only if it matches `predicate`.
|
||||
/// Also removes top-level `base_url` if it matches.
|
||||
/// Used by proxy cleanup to strip local proxy URLs without touching user-configured URLs.
|
||||
pub fn remove_codex_toml_base_url_if(toml_str: &str, predicate: impl Fn(&str) -> bool) -> String {
|
||||
let mut doc = match toml_str.parse::<DocumentMut>() {
|
||||
Ok(doc) => doc,
|
||||
Err(_) => return toml_str.to_string(),
|
||||
};
|
||||
|
||||
let model_provider = doc
|
||||
.get("model_provider")
|
||||
.and_then(|item| item.as_str())
|
||||
.map(str::to_string);
|
||||
|
||||
if let Some(provider_key) = model_provider {
|
||||
if let Some(model_providers) = doc
|
||||
.get_mut("model_providers")
|
||||
.and_then(|v| v.as_table_mut())
|
||||
{
|
||||
if let Some(provider_table) = model_providers
|
||||
.get_mut(provider_key.as_str())
|
||||
.and_then(|v| v.as_table_mut())
|
||||
{
|
||||
let should_remove = provider_table
|
||||
.get("base_url")
|
||||
.and_then(|item| item.as_str())
|
||||
.map(&predicate)
|
||||
.unwrap_or(false);
|
||||
if should_remove {
|
||||
provider_table.remove("base_url");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: also clean up top-level base_url if it matches
|
||||
let should_remove_root = doc
|
||||
.get("base_url")
|
||||
.and_then(|item| item.as_str())
|
||||
.map(&predicate)
|
||||
.unwrap_or(false);
|
||||
if should_remove_root {
|
||||
doc.as_table_mut().remove("base_url");
|
||||
}
|
||||
|
||||
doc.to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn base_url_writes_into_correct_model_provider_section() {
|
||||
let input = r#"model_provider = "any"
|
||||
model = "gpt-5.1-codex"
|
||||
|
||||
[model_providers.any]
|
||||
name = "any"
|
||||
wire_api = "responses"
|
||||
"#;
|
||||
|
||||
let result = update_codex_toml_field(input, "base_url", "https://example.com/v1").unwrap();
|
||||
let parsed: toml::Value = toml::from_str(&result).unwrap();
|
||||
|
||||
let base_url = parsed
|
||||
.get("model_providers")
|
||||
.and_then(|v| v.get("any"))
|
||||
.and_then(|v| v.get("base_url"))
|
||||
.and_then(|v| v.as_str())
|
||||
.expect("base_url should be in model_providers.any");
|
||||
assert_eq!(base_url, "https://example.com/v1");
|
||||
|
||||
// Should NOT have top-level base_url
|
||||
assert!(parsed.get("base_url").is_none());
|
||||
|
||||
// wire_api preserved
|
||||
let wire_api = parsed
|
||||
.get("model_providers")
|
||||
.and_then(|v| v.get("any"))
|
||||
.and_then(|v| v.get("wire_api"))
|
||||
.and_then(|v| v.as_str());
|
||||
assert_eq!(wire_api, Some("responses"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn base_url_creates_section_when_missing() {
|
||||
let input = r#"model_provider = "custom"
|
||||
model = "gpt-4"
|
||||
"#;
|
||||
|
||||
let result = update_codex_toml_field(input, "base_url", "https://custom.api/v1").unwrap();
|
||||
let parsed: toml::Value = toml::from_str(&result).unwrap();
|
||||
|
||||
let base_url = parsed
|
||||
.get("model_providers")
|
||||
.and_then(|v| v.get("custom"))
|
||||
.and_then(|v| v.get("base_url"))
|
||||
.and_then(|v| v.as_str())
|
||||
.expect("should create section and set base_url");
|
||||
assert_eq!(base_url, "https://custom.api/v1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn base_url_falls_back_to_top_level_without_model_provider() {
|
||||
let input = r#"model = "gpt-4"
|
||||
"#;
|
||||
|
||||
let result = update_codex_toml_field(input, "base_url", "https://fallback.api/v1").unwrap();
|
||||
let parsed: toml::Value = toml::from_str(&result).unwrap();
|
||||
|
||||
let base_url = parsed
|
||||
.get("base_url")
|
||||
.and_then(|v| v.as_str())
|
||||
.expect("should set top-level base_url");
|
||||
assert_eq!(base_url, "https://fallback.api/v1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clearing_base_url_removes_only_from_correct_section() {
|
||||
let input = r#"model_provider = "any"
|
||||
|
||||
[model_providers.any]
|
||||
name = "any"
|
||||
base_url = "https://old.api/v1"
|
||||
wire_api = "responses"
|
||||
|
||||
[mcp_servers.context7]
|
||||
command = "npx"
|
||||
"#;
|
||||
|
||||
let result = update_codex_toml_field(input, "base_url", "").unwrap();
|
||||
let parsed: toml::Value = toml::from_str(&result).unwrap();
|
||||
|
||||
// base_url removed from model_providers.any
|
||||
let any_section = parsed
|
||||
.get("model_providers")
|
||||
.and_then(|v| v.get("any"))
|
||||
.expect("model_providers.any should exist");
|
||||
assert!(any_section.get("base_url").is_none());
|
||||
|
||||
// wire_api preserved
|
||||
assert_eq!(
|
||||
any_section.get("wire_api").and_then(|v| v.as_str()),
|
||||
Some("responses")
|
||||
);
|
||||
|
||||
// mcp_servers untouched
|
||||
assert!(parsed.get("mcp_servers").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_field_operates_on_top_level() {
|
||||
let input = r#"model_provider = "any"
|
||||
model = "gpt-4"
|
||||
|
||||
[model_providers.any]
|
||||
name = "any"
|
||||
"#;
|
||||
|
||||
let result = update_codex_toml_field(input, "model", "gpt-5").unwrap();
|
||||
let parsed: toml::Value = toml::from_str(&result).unwrap();
|
||||
assert_eq!(parsed.get("model").and_then(|v| v.as_str()), Some("gpt-5"));
|
||||
|
||||
// Clear model
|
||||
let result2 = update_codex_toml_field(&result, "model", "").unwrap();
|
||||
let parsed2: toml::Value = toml::from_str(&result2).unwrap();
|
||||
assert!(parsed2.get("model").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_comments_and_whitespace() {
|
||||
let input = r#"# My Codex config
|
||||
model_provider = "any"
|
||||
model = "gpt-4"
|
||||
|
||||
# Provider section
|
||||
[model_providers.any]
|
||||
name = "any"
|
||||
base_url = "https://old.api/v1"
|
||||
"#;
|
||||
|
||||
let result = update_codex_toml_field(input, "base_url", "https://new.api/v1").unwrap();
|
||||
|
||||
// Comments should be preserved
|
||||
assert!(result.contains("# My Codex config"));
|
||||
assert!(result.contains("# Provider section"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn does_not_misplace_when_profiles_section_follows() {
|
||||
let input = r#"model_provider = "any"
|
||||
|
||||
[model_providers.any]
|
||||
name = "any"
|
||||
base_url = "https://old.api/v1"
|
||||
|
||||
[profiles.default]
|
||||
model = "gpt-4"
|
||||
"#;
|
||||
|
||||
let result = update_codex_toml_field(input, "base_url", "https://new.api/v1").unwrap();
|
||||
let parsed: toml::Value = toml::from_str(&result).unwrap();
|
||||
|
||||
// base_url in correct section
|
||||
let base_url = parsed
|
||||
.get("model_providers")
|
||||
.and_then(|v| v.get("any"))
|
||||
.and_then(|v| v.get("base_url"))
|
||||
.and_then(|v| v.as_str());
|
||||
assert_eq!(base_url, Some("https://new.api/v1"));
|
||||
|
||||
// profiles section untouched
|
||||
let profile_model = parsed
|
||||
.get("profiles")
|
||||
.and_then(|v| v.get("default"))
|
||||
.and_then(|v| v.get("model"))
|
||||
.and_then(|v| v.as_str());
|
||||
assert_eq!(profile_model, Some("gpt-4"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_base_url_if_predicate() {
|
||||
let input = r#"model_provider = "any"
|
||||
|
||||
[model_providers.any]
|
||||
name = "any"
|
||||
base_url = "http://127.0.0.1:5000/v1"
|
||||
wire_api = "responses"
|
||||
"#;
|
||||
|
||||
let result =
|
||||
remove_codex_toml_base_url_if(input, |url| url.starts_with("http://127.0.0.1"));
|
||||
let parsed: toml::Value = toml::from_str(&result).unwrap();
|
||||
|
||||
let any_section = parsed
|
||||
.get("model_providers")
|
||||
.and_then(|v| v.get("any"))
|
||||
.unwrap();
|
||||
assert!(any_section.get("base_url").is_none());
|
||||
assert_eq!(
|
||||
any_section.get("wire_api").and_then(|v| v.as_str()),
|
||||
Some("responses")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_base_url_if_keeps_non_matching() {
|
||||
let input = r#"model_provider = "any"
|
||||
|
||||
[model_providers.any]
|
||||
base_url = "https://production.api/v1"
|
||||
"#;
|
||||
|
||||
let result =
|
||||
remove_codex_toml_base_url_if(input, |url| url.starts_with("http://127.0.0.1"));
|
||||
let parsed: toml::Value = toml::from_str(&result).unwrap();
|
||||
|
||||
let base_url = parsed
|
||||
.get("model_providers")
|
||||
.and_then(|v| v.get("any"))
|
||||
.and_then(|v| v.get("base_url"))
|
||||
.and_then(|v| v.as_str());
|
||||
assert_eq!(base_url, Some("https://production.api/v1"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
use tauri::State;
|
||||
|
||||
use crate::commands::copilot::CopilotAuthState;
|
||||
use crate::proxy::providers::copilot_auth::{GitHubAccount, GitHubDeviceCodeResponse};
|
||||
|
||||
const AUTH_PROVIDER_GITHUB_COPILOT: &str = "github_copilot";
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
pub struct ManagedAuthAccount {
|
||||
pub id: String,
|
||||
pub provider: String,
|
||||
pub login: String,
|
||||
pub avatar_url: Option<String>,
|
||||
pub authenticated_at: i64,
|
||||
pub is_default: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
pub struct ManagedAuthStatus {
|
||||
pub provider: String,
|
||||
pub authenticated: bool,
|
||||
pub default_account_id: Option<String>,
|
||||
pub migration_error: Option<String>,
|
||||
pub accounts: Vec<ManagedAuthAccount>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
pub struct ManagedAuthDeviceCodeResponse {
|
||||
pub provider: String,
|
||||
pub device_code: String,
|
||||
pub user_code: String,
|
||||
pub verification_uri: String,
|
||||
pub expires_in: u64,
|
||||
pub interval: u64,
|
||||
}
|
||||
|
||||
fn ensure_auth_provider(auth_provider: &str) -> Result<&str, String> {
|
||||
match auth_provider {
|
||||
AUTH_PROVIDER_GITHUB_COPILOT => Ok(AUTH_PROVIDER_GITHUB_COPILOT),
|
||||
_ => Err(format!("Unsupported auth provider: {auth_provider}")),
|
||||
}
|
||||
}
|
||||
|
||||
fn map_account(
|
||||
provider: &str,
|
||||
account: GitHubAccount,
|
||||
default_account_id: Option<&str>,
|
||||
) -> ManagedAuthAccount {
|
||||
ManagedAuthAccount {
|
||||
is_default: default_account_id == Some(account.id.as_str()),
|
||||
id: account.id,
|
||||
provider: provider.to_string(),
|
||||
login: account.login,
|
||||
avatar_url: account.avatar_url,
|
||||
authenticated_at: account.authenticated_at,
|
||||
}
|
||||
}
|
||||
|
||||
fn map_device_code_response(
|
||||
provider: &str,
|
||||
response: GitHubDeviceCodeResponse,
|
||||
) -> ManagedAuthDeviceCodeResponse {
|
||||
ManagedAuthDeviceCodeResponse {
|
||||
provider: provider.to_string(),
|
||||
device_code: response.device_code,
|
||||
user_code: response.user_code,
|
||||
verification_uri: response.verification_uri,
|
||||
expires_in: response.expires_in,
|
||||
interval: response.interval,
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command(rename_all = "camelCase")]
|
||||
pub async fn auth_start_login(
|
||||
auth_provider: String,
|
||||
state: State<'_, CopilotAuthState>,
|
||||
) -> Result<ManagedAuthDeviceCodeResponse, String> {
|
||||
let auth_provider = ensure_auth_provider(&auth_provider)?;
|
||||
let auth_manager = state.0.read().await;
|
||||
let response = auth_manager
|
||||
.start_device_flow()
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(map_device_code_response(auth_provider, response))
|
||||
}
|
||||
|
||||
#[tauri::command(rename_all = "camelCase")]
|
||||
pub async fn auth_poll_for_account(
|
||||
auth_provider: String,
|
||||
device_code: String,
|
||||
state: State<'_, CopilotAuthState>,
|
||||
) -> Result<Option<ManagedAuthAccount>, String> {
|
||||
let auth_provider = ensure_auth_provider(&auth_provider)?;
|
||||
let auth_manager = state.0.write().await;
|
||||
match auth_manager.poll_for_token(&device_code).await {
|
||||
Ok(account) => {
|
||||
let default_account_id = auth_manager.get_status().await.default_account_id;
|
||||
Ok(account
|
||||
.map(|account| map_account(auth_provider, account, default_account_id.as_deref())))
|
||||
}
|
||||
Err(crate::proxy::providers::copilot_auth::CopilotAuthError::AuthorizationPending) => {
|
||||
Ok(None)
|
||||
}
|
||||
Err(e) => Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command(rename_all = "camelCase")]
|
||||
pub async fn auth_list_accounts(
|
||||
auth_provider: String,
|
||||
state: State<'_, CopilotAuthState>,
|
||||
) -> Result<Vec<ManagedAuthAccount>, String> {
|
||||
let auth_provider = ensure_auth_provider(&auth_provider)?;
|
||||
let auth_manager = state.0.read().await;
|
||||
let status = auth_manager.get_status().await;
|
||||
let default_account_id = status.default_account_id.clone();
|
||||
Ok(status
|
||||
.accounts
|
||||
.into_iter()
|
||||
.map(|account| map_account(auth_provider, account, default_account_id.as_deref()))
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[tauri::command(rename_all = "camelCase")]
|
||||
pub async fn auth_get_status(
|
||||
auth_provider: String,
|
||||
state: State<'_, CopilotAuthState>,
|
||||
) -> Result<ManagedAuthStatus, String> {
|
||||
let auth_provider = ensure_auth_provider(&auth_provider)?;
|
||||
let auth_manager = state.0.read().await;
|
||||
let status = auth_manager.get_status().await;
|
||||
let default_account_id = status.default_account_id.clone();
|
||||
Ok(ManagedAuthStatus {
|
||||
provider: auth_provider.to_string(),
|
||||
authenticated: status.authenticated,
|
||||
default_account_id: default_account_id.clone(),
|
||||
migration_error: status.migration_error,
|
||||
accounts: status
|
||||
.accounts
|
||||
.into_iter()
|
||||
.map(|account| map_account(auth_provider, account, default_account_id.as_deref()))
|
||||
.collect(),
|
||||
})
|
||||
}
|
||||
|
||||
#[tauri::command(rename_all = "camelCase")]
|
||||
pub async fn auth_remove_account(
|
||||
auth_provider: String,
|
||||
account_id: String,
|
||||
state: State<'_, CopilotAuthState>,
|
||||
) -> Result<(), String> {
|
||||
ensure_auth_provider(&auth_provider)?;
|
||||
let auth_manager = state.0.write().await;
|
||||
auth_manager
|
||||
.remove_account(&account_id)
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command(rename_all = "camelCase")]
|
||||
pub async fn auth_set_default_account(
|
||||
auth_provider: String,
|
||||
account_id: String,
|
||||
state: State<'_, CopilotAuthState>,
|
||||
) -> Result<(), String> {
|
||||
ensure_auth_provider(&auth_provider)?;
|
||||
let auth_manager = state.0.write().await;
|
||||
auth_manager
|
||||
.set_default_account(&account_id)
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command(rename_all = "camelCase")]
|
||||
pub async fn auth_logout(
|
||||
auth_provider: String,
|
||||
state: State<'_, CopilotAuthState>,
|
||||
) -> Result<(), String> {
|
||||
ensure_auth_provider(&auth_provider)?;
|
||||
let auth_manager = state.0.write().await;
|
||||
auth_manager.clear_auth().await.map_err(|e| e.to_string())
|
||||
}
|
||||
@@ -212,20 +212,22 @@ pub async fn set_claude_common_config_snippet(
|
||||
snippet: String,
|
||||
state: tauri::State<'_, crate::store::AppState>,
|
||||
) -> Result<(), String> {
|
||||
let is_cleared = snippet.trim().is_empty();
|
||||
|
||||
if !snippet.trim().is_empty() {
|
||||
serde_json::from_str::<serde_json::Value>(&snippet).map_err(invalid_json_format_error)?;
|
||||
}
|
||||
|
||||
let value = if snippet.trim().is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(snippet)
|
||||
};
|
||||
let value = if is_cleared { None } else { Some(snippet) };
|
||||
|
||||
state
|
||||
.db
|
||||
.set_config_snippet("claude", value)
|
||||
.map_err(|e| e.to_string())?;
|
||||
state
|
||||
.db
|
||||
.set_config_snippet_cleared("claude", is_cleared)
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -246,6 +248,7 @@ pub async fn set_common_config_snippet(
|
||||
snippet: String,
|
||||
state: tauri::State<'_, crate::store::AppState>,
|
||||
) -> Result<(), String> {
|
||||
let is_cleared = snippet.trim().is_empty();
|
||||
let old_snippet = state
|
||||
.db
|
||||
.get_config_snippet(&app_type)
|
||||
@@ -253,11 +256,7 @@ pub async fn set_common_config_snippet(
|
||||
|
||||
validate_common_config_snippet(&app_type, &snippet)?;
|
||||
|
||||
let value = if snippet.trim().is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(snippet)
|
||||
};
|
||||
let value = if is_cleared { None } else { Some(snippet) };
|
||||
|
||||
if matches!(app_type.as_str(), "claude" | "codex" | "gemini") {
|
||||
if let Some(legacy_snippet) = old_snippet
|
||||
@@ -278,6 +277,10 @@ pub async fn set_common_config_snippet(
|
||||
.db
|
||||
.set_config_snippet(&app_type, value)
|
||||
.map_err(|e| e.to_string())?;
|
||||
state
|
||||
.db
|
||||
.set_config_snippet_cleared(&app_type, is_cleared)
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
if matches!(app_type.as_str(), "claude" | "codex" | "gemini") {
|
||||
let app = AppType::from_str(&app_type).map_err(|e| e.to_string())?;
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
//! GitHub Copilot Tauri Commands
|
||||
//!
|
||||
//! 提供 Copilot OAuth 认证相关的 Tauri 命令,支持多账号管理。
|
||||
|
||||
use crate::proxy::providers::copilot_auth::{
|
||||
CopilotAuthManager, CopilotAuthStatus, CopilotModel, CopilotUsageResponse, GitHubAccount,
|
||||
GitHubDeviceCodeResponse,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
use tauri::State;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
/// Copilot 认证状态
|
||||
pub struct CopilotAuthState(pub Arc<RwLock<CopilotAuthManager>>);
|
||||
|
||||
// ==================== 设备码流程 ====================
|
||||
|
||||
/// 启动设备码流程
|
||||
///
|
||||
/// 返回设备码和用户码,用于 OAuth 认证
|
||||
#[tauri::command]
|
||||
pub async fn copilot_start_device_flow(
|
||||
state: State<'_, CopilotAuthState>,
|
||||
) -> Result<GitHubDeviceCodeResponse, String> {
|
||||
let auth_manager = state.0.read().await;
|
||||
auth_manager
|
||||
.start_device_flow()
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// 轮询 OAuth Token(向后兼容)
|
||||
///
|
||||
/// 使用设备码轮询 GitHub,等待用户完成授权
|
||||
/// 返回 true 表示授权成功,false 表示等待中
|
||||
#[tauri::command(rename_all = "camelCase")]
|
||||
pub async fn copilot_poll_for_auth(
|
||||
device_code: String,
|
||||
state: State<'_, CopilotAuthState>,
|
||||
) -> Result<bool, String> {
|
||||
let auth_manager = state.0.write().await;
|
||||
match auth_manager.poll_for_token(&device_code).await {
|
||||
Ok(Some(_account)) => {
|
||||
log::info!("[CopilotAuth] 用户已授权");
|
||||
Ok(true)
|
||||
}
|
||||
Ok(None) => Ok(false),
|
||||
Err(crate::proxy::providers::copilot_auth::CopilotAuthError::AuthorizationPending) => {
|
||||
Ok(false)
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("[CopilotAuth] 轮询失败: {e}");
|
||||
Err(e.to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 轮询 OAuth Token(多账号版本)
|
||||
///
|
||||
/// 返回新添加的账号信息,如果授权成功
|
||||
#[tauri::command(rename_all = "camelCase")]
|
||||
pub async fn copilot_poll_for_account(
|
||||
device_code: String,
|
||||
state: State<'_, CopilotAuthState>,
|
||||
) -> Result<Option<GitHubAccount>, String> {
|
||||
let auth_manager = state.0.write().await;
|
||||
match auth_manager.poll_for_token(&device_code).await {
|
||||
Ok(account) => Ok(account),
|
||||
Err(crate::proxy::providers::copilot_auth::CopilotAuthError::AuthorizationPending) => {
|
||||
Ok(None)
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("[CopilotAuth] 轮询失败: {e}");
|
||||
Err(e.to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 多账号管理 ====================
|
||||
|
||||
/// 列出所有已认证的账号
|
||||
#[tauri::command]
|
||||
pub async fn copilot_list_accounts(
|
||||
state: State<'_, CopilotAuthState>,
|
||||
) -> Result<Vec<GitHubAccount>, String> {
|
||||
let auth_manager = state.0.read().await;
|
||||
Ok(auth_manager.list_accounts().await)
|
||||
}
|
||||
|
||||
/// 移除指定账号
|
||||
#[tauri::command(rename_all = "camelCase")]
|
||||
pub async fn copilot_remove_account(
|
||||
account_id: String,
|
||||
state: State<'_, CopilotAuthState>,
|
||||
) -> Result<(), String> {
|
||||
let auth_manager = state.0.write().await;
|
||||
auth_manager
|
||||
.remove_account(&account_id)
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// 设置默认账号
|
||||
#[tauri::command(rename_all = "camelCase")]
|
||||
pub async fn copilot_set_default_account(
|
||||
account_id: String,
|
||||
state: State<'_, CopilotAuthState>,
|
||||
) -> Result<(), String> {
|
||||
let auth_manager = state.0.write().await;
|
||||
auth_manager
|
||||
.set_default_account(&account_id)
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
// ==================== 状态查询 ====================
|
||||
|
||||
/// 获取认证状态(包含所有账号)
|
||||
#[tauri::command]
|
||||
pub async fn copilot_get_auth_status(
|
||||
state: State<'_, CopilotAuthState>,
|
||||
) -> Result<CopilotAuthStatus, String> {
|
||||
let auth_manager = state.0.read().await;
|
||||
Ok(auth_manager.get_status().await)
|
||||
}
|
||||
|
||||
/// 检查是否已认证(有任意账号)
|
||||
#[tauri::command]
|
||||
pub async fn copilot_is_authenticated(state: State<'_, CopilotAuthState>) -> Result<bool, String> {
|
||||
let auth_manager = state.0.read().await;
|
||||
Ok(auth_manager.is_authenticated().await)
|
||||
}
|
||||
|
||||
/// 注销所有 Copilot 认证
|
||||
#[tauri::command]
|
||||
pub async fn copilot_logout(state: State<'_, CopilotAuthState>) -> Result<(), String> {
|
||||
let auth_manager = state.0.write().await;
|
||||
auth_manager.clear_auth().await.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
// ==================== Token 获取 ====================
|
||||
|
||||
/// 获取有效的 Copilot Token(向后兼容:使用第一个账号)
|
||||
///
|
||||
/// 内部使用,用于代理请求
|
||||
#[tauri::command]
|
||||
pub async fn copilot_get_token(state: State<'_, CopilotAuthState>) -> Result<String, String> {
|
||||
let auth_manager = state.0.read().await;
|
||||
auth_manager
|
||||
.get_valid_token()
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// 获取指定账号的有效 Copilot Token
|
||||
#[tauri::command(rename_all = "camelCase")]
|
||||
pub async fn copilot_get_token_for_account(
|
||||
account_id: String,
|
||||
state: State<'_, CopilotAuthState>,
|
||||
) -> Result<String, String> {
|
||||
let auth_manager = state.0.read().await;
|
||||
auth_manager
|
||||
.get_valid_token_for_account(&account_id)
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
// ==================== 模型和使用量 ====================
|
||||
|
||||
/// 获取 Copilot 可用模型列表(向后兼容:使用第一个账号)
|
||||
#[tauri::command]
|
||||
pub async fn copilot_get_models(
|
||||
state: State<'_, CopilotAuthState>,
|
||||
) -> Result<Vec<CopilotModel>, String> {
|
||||
let auth_manager = state.0.read().await;
|
||||
auth_manager.fetch_models().await.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// 获取指定账号的 Copilot 可用模型列表
|
||||
#[tauri::command(rename_all = "camelCase")]
|
||||
pub async fn copilot_get_models_for_account(
|
||||
account_id: String,
|
||||
state: State<'_, CopilotAuthState>,
|
||||
) -> Result<Vec<CopilotModel>, String> {
|
||||
let auth_manager = state.0.read().await;
|
||||
auth_manager
|
||||
.fetch_models_for_account(&account_id)
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// 获取 Copilot 使用量信息(向后兼容:使用第一个账号)
|
||||
#[tauri::command]
|
||||
pub async fn copilot_get_usage(
|
||||
state: State<'_, CopilotAuthState>,
|
||||
) -> Result<CopilotUsageResponse, String> {
|
||||
let auth_manager = state.0.read().await;
|
||||
auth_manager.fetch_usage().await.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// 获取指定账号的 Copilot 使用量信息
|
||||
#[tauri::command(rename_all = "camelCase")]
|
||||
pub async fn copilot_get_usage_for_account(
|
||||
account_id: String,
|
||||
state: State<'_, CopilotAuthState>,
|
||||
) -> Result<CopilotUsageResponse, String> {
|
||||
let auth_manager = state.0.read().await;
|
||||
auth_manager
|
||||
.fetch_usage_for_account(&account_id)
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
@@ -115,7 +115,7 @@ pub async fn open_zip_file_dialog<R: tauri::Runtime>(
|
||||
let dialog = app.dialog();
|
||||
let result = dialog
|
||||
.file()
|
||||
.add_filter("ZIP", &["zip"])
|
||||
.add_filter("ZIP / Skill", &["zip", "skill"])
|
||||
.blocking_pick_file();
|
||||
|
||||
Ok(result.map(|p| p.to_string()))
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
#[tauri::command]
|
||||
pub fn enter_lightweight_mode(app: tauri::AppHandle) -> Result<(), String> {
|
||||
crate::lightweight::enter_lightweight_mode(&app)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn exit_lightweight_mode(app: tauri::AppHandle) -> Result<(), String> {
|
||||
crate::lightweight::exit_lightweight_mode(&app)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn is_lightweight_mode() -> bool {
|
||||
crate::lightweight::is_lightweight_mode()
|
||||
}
|
||||
+188
-13
@@ -6,7 +6,7 @@ use crate::services::ProviderService;
|
||||
use once_cell::sync::Lazy;
|
||||
use regex::Regex;
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::str::FromStr;
|
||||
use tauri::AppHandle;
|
||||
use tauri::State;
|
||||
@@ -500,7 +500,8 @@ fn extend_from_path_list(
|
||||
|
||||
/// OpenCode install.sh 路径优先级(见 https://github.com/anomalyco/opencode README):
|
||||
/// $OPENCODE_INSTALL_DIR > $XDG_BIN_DIR > $HOME/bin > $HOME/.opencode/bin
|
||||
/// 额外扫描 Go 安装路径(~/go/bin、$GOPATH/*/bin)。
|
||||
/// 额外扫描 Bun 默认全局安装路径(~/.bun/bin)
|
||||
/// 和 Go 安装路径(~/go/bin、$GOPATH/*/bin)。
|
||||
fn opencode_extra_search_paths(
|
||||
home: &Path,
|
||||
opencode_install_dir: Option<std::ffi::OsString>,
|
||||
@@ -515,6 +516,7 @@ fn opencode_extra_search_paths(
|
||||
if !home.as_os_str().is_empty() {
|
||||
push_unique_path(&mut paths, home.join("bin"));
|
||||
push_unique_path(&mut paths, home.join(".opencode").join("bin"));
|
||||
push_unique_path(&mut paths, home.join(".bun").join("bin"));
|
||||
push_unique_path(&mut paths, home.join("go").join("bin"));
|
||||
}
|
||||
|
||||
@@ -718,8 +720,10 @@ pub async fn open_provider_terminal(
|
||||
state: State<'_, crate::store::AppState>,
|
||||
app: String,
|
||||
#[allow(non_snake_case)] providerId: String,
|
||||
cwd: Option<String>,
|
||||
) -> Result<bool, String> {
|
||||
let app_type = AppType::from_str(&app).map_err(|e| e.to_string())?;
|
||||
let launch_cwd = resolve_launch_cwd(cwd)?;
|
||||
|
||||
// 获取提供商配置
|
||||
let providers = ProviderService::list(state.inner(), app_type.clone())
|
||||
@@ -734,7 +738,8 @@ pub async fn open_provider_terminal(
|
||||
let env_vars = extract_env_vars_from_config(config, &app_type);
|
||||
|
||||
// 根据平台启动终端,传入提供商ID用于生成唯一的配置文件名
|
||||
launch_terminal_with_env(env_vars, &providerId).map_err(|e| format!("启动终端失败: {e}"))?;
|
||||
launch_terminal_with_env(env_vars, &providerId, launch_cwd.as_deref())
|
||||
.map_err(|e| format!("启动终端失败: {e}"))?;
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
@@ -789,11 +794,49 @@ fn extract_env_vars_from_config(
|
||||
env_vars
|
||||
}
|
||||
|
||||
fn resolve_launch_cwd(cwd: Option<String>) -> Result<Option<PathBuf>, String> {
|
||||
let Some(raw_path) = cwd.filter(|value| !value.trim().is_empty()) else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
if raw_path.contains('\n') || raw_path.contains('\r') {
|
||||
return Err("目录路径包含非法换行符".to_string());
|
||||
}
|
||||
|
||||
let path = Path::new(&raw_path);
|
||||
if !path.exists() {
|
||||
return Err(format!("目录不存在: {raw_path}"));
|
||||
}
|
||||
|
||||
let resolved = std::fs::canonicalize(path).map_err(|e| format!("解析目录失败: {e}"))?;
|
||||
if !resolved.is_dir() {
|
||||
return Err(format!("选择的路径不是文件夹: {}", resolved.display()));
|
||||
}
|
||||
|
||||
// Strip Windows extended-length prefix that canonicalize produces,
|
||||
// as it can break batch scripts and other shell commands.
|
||||
// Special-case \\?\UNC\server\share -> \\server\share for network/WSL paths.
|
||||
#[cfg(target_os = "windows")]
|
||||
let resolved = {
|
||||
let s = resolved.to_string_lossy();
|
||||
if let Some(unc) = s.strip_prefix(r"\\?\UNC\") {
|
||||
PathBuf::from(format!(r"\\{unc}"))
|
||||
} else if let Some(stripped) = s.strip_prefix(r"\\?\") {
|
||||
PathBuf::from(stripped)
|
||||
} else {
|
||||
resolved
|
||||
}
|
||||
};
|
||||
|
||||
Ok(Some(resolved))
|
||||
}
|
||||
|
||||
/// 创建临时配置文件并启动 claude 终端
|
||||
/// 使用 --settings 参数传入提供商特定的 API 配置
|
||||
fn launch_terminal_with_env(
|
||||
env_vars: Vec<(String, String)>,
|
||||
provider_id: &str,
|
||||
cwd: Option<&Path>,
|
||||
) -> Result<(), String> {
|
||||
let temp_dir = std::env::temp_dir();
|
||||
let config_file = temp_dir.join(format!(
|
||||
@@ -807,19 +850,19 @@ fn launch_terminal_with_env(
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
launch_macos_terminal(&config_file)?;
|
||||
launch_macos_terminal(&config_file, cwd)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
launch_linux_terminal(&config_file)?;
|
||||
launch_linux_terminal(&config_file, cwd)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
launch_windows_terminal(&temp_dir, &config_file)?;
|
||||
launch_windows_terminal(&temp_dir, &config_file, cwd)?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -849,7 +892,7 @@ fn write_claude_config(
|
||||
|
||||
/// macOS: 根据用户首选终端启动
|
||||
#[cfg(target_os = "macos")]
|
||||
fn launch_macos_terminal(config_file: &std::path::Path) -> Result<(), String> {
|
||||
fn launch_macos_terminal(config_file: &std::path::Path, cwd: Option<&Path>) -> Result<(), String> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let preferred = crate::settings::get_preferred_terminal();
|
||||
@@ -858,18 +901,21 @@ fn launch_macos_terminal(config_file: &std::path::Path) -> Result<(), String> {
|
||||
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);
|
||||
|
||||
// Write the shell script to a temp file
|
||||
let script_content = format!(
|
||||
r#"#!/bin/bash
|
||||
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
|
||||
"#,
|
||||
config_path = config_path,
|
||||
script_file = script_file.display()
|
||||
script_file = script_file.display(),
|
||||
cd_command = cd_command,
|
||||
);
|
||||
|
||||
std::fs::write(&script_file, &script_content).map_err(|e| format!("写入启动脚本失败: {e}"))?;
|
||||
@@ -1005,7 +1051,7 @@ fn launch_macos_open_app(
|
||||
|
||||
/// Linux: 根据用户首选终端启动
|
||||
#[cfg(target_os = "linux")]
|
||||
fn launch_linux_terminal(config_file: &std::path::Path) -> Result<(), String> {
|
||||
fn launch_linux_terminal(config_file: &std::path::Path, cwd: Option<&Path>) -> Result<(), String> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::process::Command;
|
||||
|
||||
@@ -1027,17 +1073,20 @@ fn launch_linux_terminal(config_file: &std::path::Path) -> Result<(), String> {
|
||||
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 script_content = format!(
|
||||
r#"#!/bin/bash
|
||||
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
|
||||
"#,
|
||||
config_path = config_path,
|
||||
script_file = script_file.display()
|
||||
script_file = script_file.display(),
|
||||
cd_command = cd_command,
|
||||
);
|
||||
|
||||
std::fs::write(&script_file, &script_content).map_err(|e| format!("写入启动脚本失败: {e}"))?;
|
||||
@@ -1116,22 +1165,28 @@ fn which_command(cmd: &str) -> bool {
|
||||
fn launch_windows_terminal(
|
||||
temp_dir: &std::path::Path,
|
||||
config_file: &std::path::Path,
|
||||
cwd: Option<&Path>,
|
||||
) -> Result<(), String> {
|
||||
let preferred = crate::settings::get_preferred_terminal();
|
||||
let terminal = preferred.as_deref().unwrap_or("cmd");
|
||||
|
||||
let bat_file = temp_dir.join(format!("cc_switch_claude_{}.bat", std::process::id()));
|
||||
let config_path_for_batch = config_file.to_string_lossy().replace('&', "^&");
|
||||
let config_path_for_batch = escape_windows_batch_value(&config_file.to_string_lossy());
|
||||
let cwd_command = build_windows_cwd_command(cwd);
|
||||
|
||||
let content = format!(
|
||||
"@echo off
|
||||
{cwd_command}
|
||||
echo Using provider-specific claude config:
|
||||
echo {}
|
||||
claude --settings \"{}\"
|
||||
del \"{}\" >nul 2>&1
|
||||
del \"%~f0\" >nul 2>&1
|
||||
",
|
||||
config_path_for_batch, config_path_for_batch, config_path_for_batch
|
||||
config_path_for_batch,
|
||||
config_path_for_batch,
|
||||
config_path_for_batch,
|
||||
cwd_command = cwd_command,
|
||||
);
|
||||
|
||||
std::fs::write(&bat_file, &content).map_err(|e| format!("写入批处理文件失败: {e}"))?;
|
||||
@@ -1162,6 +1217,55 @@ 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('\'', "'\"'\"'"))
|
||||
}
|
||||
|
||||
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||
fn is_windows_unc_path(path: &str) -> bool {
|
||||
path.starts_with(r"\\")
|
||||
}
|
||||
|
||||
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||
fn build_windows_cwd_command_str(path: &str) -> String {
|
||||
let escaped = escape_windows_batch_value(path);
|
||||
|
||||
if is_windows_unc_path(path) {
|
||||
// `cmd.exe` cannot make a UNC path current via `cd`; `pushd` maps it first.
|
||||
format!("pushd \"{escaped}\" || exit /b 1\r\n")
|
||||
} else {
|
||||
format!("cd /d \"{escaped}\" || exit /b 1\r\n")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn build_windows_cwd_command(cwd: Option<&Path>) -> String {
|
||||
cwd.map(|dir| build_windows_cwd_command_str(&dir.to_string_lossy()))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||
fn escape_windows_batch_value(value: &str) -> String {
|
||||
value
|
||||
.replace('^', "^^")
|
||||
.replace('%', "%%")
|
||||
.replace('&', "^&")
|
||||
.replace('|', "^|")
|
||||
.replace('<', "^<")
|
||||
.replace('>', "^>")
|
||||
.replace('(', "^(")
|
||||
.replace(')', "^)")
|
||||
}
|
||||
/// Windows: Run a start command with common error handling
|
||||
#[cfg(target_os = "windows")]
|
||||
fn run_windows_start_command(args: &[&str], terminal_name: &str) -> Result<(), String> {
|
||||
@@ -1280,6 +1384,7 @@ mod tests {
|
||||
assert_eq!(paths[1], PathBuf::from("/xdg/bin"));
|
||||
assert!(paths.contains(&PathBuf::from("/home/tester/bin")));
|
||||
assert!(paths.contains(&PathBuf::from("/home/tester/.opencode/bin")));
|
||||
assert!(paths.contains(&PathBuf::from("/home/tester/.bun/bin")));
|
||||
assert!(paths.contains(&PathBuf::from("/home/tester/go/bin")));
|
||||
assert!(paths.contains(&PathBuf::from("/go/path1/bin")));
|
||||
assert!(paths.contains(&PathBuf::from("/go/path2/bin")));
|
||||
@@ -1290,7 +1395,7 @@ mod tests {
|
||||
let home = PathBuf::from("/home/tester");
|
||||
let same_dir = Some(std::ffi::OsString::from("/same/path"));
|
||||
|
||||
let paths = opencode_extra_search_paths(&home, same_dir.clone(), same_dir.clone(), None);
|
||||
let paths = opencode_extra_search_paths(&home, same_dir.clone(), same_dir, None);
|
||||
|
||||
let count = paths
|
||||
.iter()
|
||||
@@ -1299,6 +1404,18 @@ mod tests {
|
||||
assert_eq!(count, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opencode_extra_search_paths_deduplicates_bun_default_dir() {
|
||||
let home = PathBuf::from("/home/tester");
|
||||
let paths = opencode_extra_search_paths(&home, None, None, None);
|
||||
|
||||
let count = paths
|
||||
.iter()
|
||||
.filter(|path| **path == PathBuf::from("/home/tester/.bun/bin"))
|
||||
.count();
|
||||
assert_eq!(count, 1);
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
#[test]
|
||||
fn tool_executable_candidates_non_windows_uses_plain_binary_name() {
|
||||
@@ -1323,4 +1440,62 @@ mod tests {
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_launch_cwd_accepts_existing_directory() {
|
||||
let resolved =
|
||||
resolve_launch_cwd(Some(std::env::temp_dir().to_string_lossy().into_owned()))
|
||||
.expect("temp dir should resolve")
|
||||
.expect("temp dir should be present");
|
||||
|
||||
assert!(resolved.is_dir());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_launch_cwd_rejects_missing_directory() {
|
||||
let unique = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.expect("clock should be after epoch")
|
||||
.as_nanos();
|
||||
let missing = std::env::temp_dir().join(format!("cc-switch-missing-{unique}"));
|
||||
|
||||
let error = resolve_launch_cwd(Some(missing.to_string_lossy().into_owned()))
|
||||
.expect_err("missing directory should fail");
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_windows_cwd_command_str_uses_cd_for_drive_paths() {
|
||||
let command = build_windows_cwd_command_str(r"C:\work\repo");
|
||||
|
||||
assert_eq!(command, "cd /d \"C:\\work\\repo\" || exit /b 1\r\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_windows_cwd_command_str_uses_pushd_for_unc_paths() {
|
||||
let command = build_windows_cwd_command_str(r"\\wsl$\Ubuntu\home\coder\repo");
|
||||
|
||||
assert_eq!(
|
||||
command,
|
||||
"pushd \"\\\\wsl$\\Ubuntu\\home\\coder\\repo\" || exit /b 1\r\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_windows_cwd_command_str_escapes_batch_metacharacters() {
|
||||
let command = build_windows_cwd_command_str(r"\\server\share\100%&(test)");
|
||||
|
||||
assert_eq!(
|
||||
command,
|
||||
"pushd \"\\\\server\\share\\100%%^&^(test^)\" || exit /b 1\r\n"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
#![allow(non_snake_case)]
|
||||
|
||||
mod auth;
|
||||
mod config;
|
||||
mod copilot;
|
||||
mod deeplink;
|
||||
mod env;
|
||||
mod failover;
|
||||
@@ -19,11 +21,15 @@ mod settings;
|
||||
pub mod skill;
|
||||
mod stream_check;
|
||||
mod sync_support;
|
||||
|
||||
mod lightweight;
|
||||
mod usage;
|
||||
mod webdav_sync;
|
||||
mod workspace;
|
||||
|
||||
pub use auth::*;
|
||||
pub use config::*;
|
||||
pub use copilot::*;
|
||||
pub use deeplink::*;
|
||||
pub use env::*;
|
||||
pub use failover::*;
|
||||
@@ -41,6 +47,8 @@ pub use session_manager::*;
|
||||
pub use settings::*;
|
||||
pub use skill::*;
|
||||
pub use stream_check::*;
|
||||
|
||||
pub use lightweight::*;
|
||||
pub use usage::*;
|
||||
pub use webdav_sync::*;
|
||||
pub use workspace::*;
|
||||
|
||||
@@ -2,6 +2,7 @@ use indexmap::IndexMap;
|
||||
use tauri::State;
|
||||
|
||||
use crate::app_config::AppType;
|
||||
use crate::commands::copilot::CopilotAuthState;
|
||||
use crate::error::AppError;
|
||||
use crate::provider::Provider;
|
||||
use crate::services::{
|
||||
@@ -10,6 +11,11 @@ use crate::services::{
|
||||
use crate::store::AppState;
|
||||
use std::str::FromStr;
|
||||
|
||||
// 常量定义
|
||||
const TEMPLATE_TYPE_GITHUB_COPILOT: &str = "github_copilot";
|
||||
const COPILOT_UNIT_PREMIUM: &str = "requests";
|
||||
|
||||
/// 获取所有供应商
|
||||
#[tauri::command]
|
||||
pub fn get_providers(
|
||||
state: State<'_, AppState>,
|
||||
@@ -30,9 +36,11 @@ pub fn add_provider(
|
||||
state: State<'_, AppState>,
|
||||
app: String,
|
||||
provider: Provider,
|
||||
#[allow(non_snake_case)] addToLive: Option<bool>,
|
||||
) -> Result<bool, String> {
|
||||
let app_type = AppType::from_str(&app).map_err(|e| e.to_string())?;
|
||||
ProviderService::add(state.inner(), app_type, provider).map_err(|e| e.to_string())
|
||||
ProviderService::add(state.inner(), app_type, provider, addToLive.unwrap_or(true))
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -40,9 +48,11 @@ pub fn update_provider(
|
||||
state: State<'_, AppState>,
|
||||
app: String,
|
||||
provider: Provider,
|
||||
#[allow(non_snake_case)] originalId: Option<String>,
|
||||
) -> Result<bool, String> {
|
||||
let app_type = AppType::from_str(&app).map_err(|e| e.to_string())?;
|
||||
ProviderService::update(state.inner(), app_type, provider).map_err(|e| e.to_string())
|
||||
ProviderService::update(state.inner(), app_type, originalId.as_deref(), provider)
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -103,20 +113,22 @@ fn import_default_config_internal(state: &AppState, app_type: AppType) -> Result
|
||||
// Extract common config snippet (mirrors old startup logic in lib.rs)
|
||||
if state
|
||||
.db
|
||||
.get_config_snippet(app_type.as_str())
|
||||
.ok()
|
||||
.flatten()
|
||||
.is_none()
|
||||
.should_auto_extract_config_snippet(app_type.as_str())?
|
||||
{
|
||||
match ProviderService::extract_common_config_snippet(state, app_type.clone()) {
|
||||
Ok(snippet) if !snippet.is_empty() && snippet != "{}" => {
|
||||
let _ = state
|
||||
.db
|
||||
.set_config_snippet(app_type.as_str(), Some(snippet));
|
||||
let _ = state
|
||||
.db
|
||||
.set_config_snippet_cleared(app_type.as_str(), false);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
ProviderService::migrate_legacy_common_config_usage_if_needed(state, app_type.clone())?;
|
||||
}
|
||||
|
||||
Ok(imported)
|
||||
@@ -140,10 +152,65 @@ pub fn import_default_config(state: State<'_, AppState>, app: String) -> Result<
|
||||
#[tauri::command]
|
||||
pub async fn queryProviderUsage(
|
||||
state: State<'_, AppState>,
|
||||
copilot_state: State<'_, CopilotAuthState>,
|
||||
#[allow(non_snake_case)] providerId: String, // 使用 camelCase 匹配前端
|
||||
app: String,
|
||||
) -> Result<crate::provider::UsageResult, String> {
|
||||
let app_type = AppType::from_str(&app).map_err(|e| e.to_string())?;
|
||||
|
||||
// 检查是否为 GitHub Copilot 模板类型,并解析绑定账号
|
||||
let (is_copilot_template, copilot_account_id) = {
|
||||
let providers = state
|
||||
.db
|
||||
.get_all_providers(app_type.as_str())
|
||||
.map_err(|e| format!("Failed to get providers: {e}"))?;
|
||||
|
||||
let provider = providers.get(&providerId);
|
||||
let is_copilot = provider
|
||||
.and_then(|p| p.meta.as_ref())
|
||||
.and_then(|m| m.usage_script.as_ref())
|
||||
.and_then(|s| s.template_type.as_ref())
|
||||
.map(|t| t == TEMPLATE_TYPE_GITHUB_COPILOT)
|
||||
.unwrap_or(false);
|
||||
let account_id = provider
|
||||
.and_then(|p| p.meta.as_ref())
|
||||
.and_then(|m| m.managed_account_id_for(TEMPLATE_TYPE_GITHUB_COPILOT));
|
||||
|
||||
(is_copilot, account_id)
|
||||
};
|
||||
|
||||
if is_copilot_template {
|
||||
// 使用 Copilot 专用 API
|
||||
let auth_manager = copilot_state.0.read().await;
|
||||
let usage = match copilot_account_id.as_deref() {
|
||||
Some(account_id) => auth_manager
|
||||
.fetch_usage_for_account(account_id)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to fetch Copilot usage: {e}"))?,
|
||||
None => auth_manager
|
||||
.fetch_usage()
|
||||
.await
|
||||
.map_err(|e| format!("Failed to fetch Copilot usage: {e}"))?,
|
||||
};
|
||||
let premium = &usage.quota_snapshots.premium_interactions;
|
||||
let used = premium.entitlement - premium.remaining;
|
||||
|
||||
return Ok(crate::provider::UsageResult {
|
||||
success: true,
|
||||
data: Some(vec![crate::provider::UsageData {
|
||||
plan_name: Some(usage.copilot_plan),
|
||||
remaining: Some(premium.remaining as f64),
|
||||
total: Some(premium.entitlement as f64),
|
||||
used: Some(used as f64),
|
||||
unit: Some(COPILOT_UNIT_PREMIUM.to_string()),
|
||||
is_valid: Some(true),
|
||||
invalid_message: None,
|
||||
extra: Some(format!("Reset: {}", usage.quota_reset_date)),
|
||||
}]),
|
||||
error: None,
|
||||
});
|
||||
}
|
||||
|
||||
ProviderService::query_usage(state.inner(), app_type, &providerId)
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
|
||||
@@ -74,3 +74,12 @@ pub async fn delete_session(
|
||||
.await
|
||||
.map_err(|e| format!("Failed to delete session: {e}"))?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn delete_sessions(
|
||||
items: Vec<session_manager::DeleteSessionRequest>,
|
||||
) -> Result<Vec<session_manager::DeleteSessionOutcome>, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || session_manager::delete_sessions(&items))
|
||||
.await
|
||||
.map_err(|e| format!("Failed to delete sessions: {e}"))
|
||||
}
|
||||
|
||||
@@ -6,8 +6,20 @@ fn merge_settings_for_save(
|
||||
mut incoming: crate::settings::AppSettings,
|
||||
existing: &crate::settings::AppSettings,
|
||||
) -> crate::settings::AppSettings {
|
||||
if incoming.webdav_sync.is_none() {
|
||||
incoming.webdav_sync = existing.webdav_sync.clone();
|
||||
match (&mut incoming.webdav_sync, &existing.webdav_sync) {
|
||||
// incoming 没有 webdav → 保留现有
|
||||
(None, _) => {
|
||||
incoming.webdav_sync = existing.webdav_sync.clone();
|
||||
}
|
||||
// incoming 有 webdav 但密码为空,且现有有密码 → 填回现有密码
|
||||
// (get_settings_for_frontend 总是清空密码,所以通过 save_settings
|
||||
// 传入的空密码意味着"保持现有"而非"用户主动清空")
|
||||
(Some(incoming_sync), Some(existing_sync))
|
||||
if incoming_sync.password.is_empty() && !existing_sync.password.is_empty() =>
|
||||
{
|
||||
incoming_sync.password = existing_sync.password.clone();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
incoming
|
||||
}
|
||||
@@ -116,6 +128,66 @@ mod tests {
|
||||
Some("https://dav.new.example.com")
|
||||
);
|
||||
}
|
||||
|
||||
/// Regression test: frontend always receives empty password from
|
||||
/// get_settings_for_frontend(). If a component accidentally spreads
|
||||
/// the full settings object into save_settings, the empty password
|
||||
/// must NOT overwrite the existing one.
|
||||
#[test]
|
||||
fn save_settings_should_preserve_password_when_incoming_has_empty_password() {
|
||||
let mut existing = AppSettings::default();
|
||||
existing.webdav_sync = Some(WebDavSyncSettings {
|
||||
base_url: "https://dav.example.com".to_string(),
|
||||
username: "alice".to_string(),
|
||||
password: "secret".to_string(),
|
||||
..WebDavSyncSettings::default()
|
||||
});
|
||||
|
||||
// Simulate frontend sending settings with cleared password
|
||||
let mut incoming = AppSettings::default();
|
||||
incoming.webdav_sync = Some(WebDavSyncSettings {
|
||||
base_url: "https://dav.example.com".to_string(),
|
||||
username: "alice".to_string(),
|
||||
password: "".to_string(),
|
||||
..WebDavSyncSettings::default()
|
||||
});
|
||||
|
||||
let merged = merge_settings_for_save(incoming, &existing);
|
||||
|
||||
assert_eq!(
|
||||
merged.webdav_sync.as_ref().map(|v| v.password.as_str()),
|
||||
Some("secret"),
|
||||
"empty password from frontend must not overwrite existing password"
|
||||
);
|
||||
}
|
||||
|
||||
/// When both incoming and existing have no password, merge should
|
||||
/// work without panicking and keep the empty state.
|
||||
#[test]
|
||||
fn save_settings_should_handle_both_empty_passwords() {
|
||||
let mut existing = AppSettings::default();
|
||||
existing.webdav_sync = Some(WebDavSyncSettings {
|
||||
base_url: "https://dav.example.com".to_string(),
|
||||
username: "alice".to_string(),
|
||||
password: "".to_string(),
|
||||
..WebDavSyncSettings::default()
|
||||
});
|
||||
|
||||
let mut incoming = AppSettings::default();
|
||||
incoming.webdav_sync = Some(WebDavSyncSettings {
|
||||
base_url: "https://dav.example.com".to_string(),
|
||||
username: "alice".to_string(),
|
||||
password: "".to_string(),
|
||||
..WebDavSyncSettings::default()
|
||||
});
|
||||
|
||||
let merged = merge_settings_for_save(incoming, &existing);
|
||||
|
||||
assert_eq!(
|
||||
merged.webdav_sync.as_ref().map(|v| v.password.as_str()),
|
||||
Some("")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 获取开机自启状态
|
||||
|
||||
@@ -6,7 +6,10 @@
|
||||
|
||||
use crate::app_config::{AppType, InstalledSkill, UnmanagedSkill};
|
||||
use crate::error::format_skill_error;
|
||||
use crate::services::skill::{DiscoverableSkill, Skill, SkillRepo, SkillService};
|
||||
use crate::services::skill::{
|
||||
DiscoverableSkill, ImportSkillSelection, Skill, SkillBackupEntry, SkillRepo, SkillService,
|
||||
SkillUninstallResult,
|
||||
};
|
||||
use crate::store::AppState;
|
||||
use std::sync::Arc;
|
||||
use tauri::State;
|
||||
@@ -33,6 +36,17 @@ pub fn get_installed_skills(app_state: State<'_, AppState>) -> Result<Vec<Instal
|
||||
SkillService::get_all_installed(&app_state.db).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn get_skill_backups() -> Result<Vec<SkillBackupEntry>, String> {
|
||||
SkillService::list_backups().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn delete_skill_backup(backup_id: String) -> Result<bool, String> {
|
||||
SkillService::delete_backup(&backup_id).map_err(|e| e.to_string())?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// 安装 Skill(新版统一安装)
|
||||
///
|
||||
/// 参数:
|
||||
@@ -56,9 +70,22 @@ pub async fn install_skill_unified(
|
||||
|
||||
/// 卸载 Skill(新版统一卸载)
|
||||
#[tauri::command]
|
||||
pub fn uninstall_skill_unified(id: String, app_state: State<'_, AppState>) -> Result<bool, String> {
|
||||
SkillService::uninstall(&app_state.db, &id).map_err(|e| e.to_string())?;
|
||||
Ok(true)
|
||||
pub fn uninstall_skill_unified(
|
||||
id: String,
|
||||
app_state: State<'_, AppState>,
|
||||
) -> Result<SkillUninstallResult, String> {
|
||||
SkillService::uninstall(&app_state.db, &id).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn restore_skill_backup(
|
||||
backup_id: String,
|
||||
current_app: String,
|
||||
app_state: State<'_, AppState>,
|
||||
) -> Result<InstalledSkill, String> {
|
||||
let app_type = parse_app_type(¤t_app)?;
|
||||
SkillService::restore_from_backup(&app_state.db, &backup_id, &app_type)
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// 切换 Skill 的应用启用状态
|
||||
@@ -85,10 +112,10 @@ pub fn scan_unmanaged_skills(
|
||||
/// 从应用目录导入 Skills
|
||||
#[tauri::command]
|
||||
pub fn import_skills_from_apps(
|
||||
directories: Vec<String>,
|
||||
imports: Vec<ImportSkillSelection>,
|
||||
app_state: State<'_, AppState>,
|
||||
) -> Result<Vec<InstalledSkill>, String> {
|
||||
SkillService::import_from_apps(&app_state.db, directories).map_err(|e| e.to_string())
|
||||
SkillService::import_from_apps(&app_state.db, imports).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
// ========== 发现功能命令 ==========
|
||||
@@ -192,7 +219,10 @@ pub async fn install_skill_for_app(
|
||||
|
||||
/// 卸载技能(兼容旧 API)
|
||||
#[tauri::command]
|
||||
pub fn uninstall_skill(directory: String, app_state: State<'_, AppState>) -> Result<bool, String> {
|
||||
pub fn uninstall_skill(
|
||||
directory: String,
|
||||
app_state: State<'_, AppState>,
|
||||
) -> Result<SkillUninstallResult, String> {
|
||||
uninstall_skill_for_app("claude".to_string(), directory, app_state)
|
||||
}
|
||||
|
||||
@@ -202,7 +232,7 @@ pub fn uninstall_skill_for_app(
|
||||
app: String,
|
||||
directory: String,
|
||||
app_state: State<'_, AppState>,
|
||||
) -> Result<bool, String> {
|
||||
) -> Result<SkillUninstallResult, String> {
|
||||
let _ = parse_app_type(&app)?; // 验证参数
|
||||
|
||||
// 通过 directory 找到对应的 skill id
|
||||
@@ -213,9 +243,7 @@ pub fn uninstall_skill_for_app(
|
||||
.find(|s| s.directory.eq_ignore_ascii_case(&directory))
|
||||
.ok_or_else(|| format!("未找到已安装的 Skill: {directory}"))?;
|
||||
|
||||
SkillService::uninstall(&app_state.db, &skill.id).map_err(|e| e.to_string())?;
|
||||
|
||||
Ok(true)
|
||||
SkillService::uninstall(&app_state.db, &skill.id).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
// ========== 仓库管理命令 ==========
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! 流式健康检查命令
|
||||
|
||||
use crate::app_config::AppType;
|
||||
use crate::commands::copilot::CopilotAuthState;
|
||||
use crate::error::AppError;
|
||||
use crate::services::stream_check::{
|
||||
HealthStatus, StreamCheckConfig, StreamCheckResult, StreamCheckService,
|
||||
@@ -13,6 +14,7 @@ use tauri::State;
|
||||
#[tauri::command]
|
||||
pub async fn stream_check_provider(
|
||||
state: State<'_, AppState>,
|
||||
copilot_state: State<'_, CopilotAuthState>,
|
||||
app_type: AppType,
|
||||
provider_id: String,
|
||||
) -> Result<StreamCheckResult, AppError> {
|
||||
@@ -23,7 +25,23 @@ pub async fn stream_check_provider(
|
||||
.get(&provider_id)
|
||||
.ok_or_else(|| AppError::Message(format!("供应商 {provider_id} 不存在")))?;
|
||||
|
||||
let result = StreamCheckService::check_with_retry(&app_type, provider, &config).await?;
|
||||
let auth_override = resolve_copilot_auth_override(provider, &copilot_state).await?;
|
||||
let claude_api_format_override = resolve_claude_api_format_override(
|
||||
&app_type,
|
||||
provider,
|
||||
&config,
|
||||
&copilot_state,
|
||||
auth_override.as_ref(),
|
||||
)
|
||||
.await?;
|
||||
let result = StreamCheckService::check_with_retry(
|
||||
&app_type,
|
||||
provider,
|
||||
&config,
|
||||
auth_override,
|
||||
claude_api_format_override,
|
||||
)
|
||||
.await?;
|
||||
|
||||
// 记录日志
|
||||
let _ =
|
||||
@@ -38,6 +56,7 @@ pub async fn stream_check_provider(
|
||||
#[tauri::command]
|
||||
pub async fn stream_check_all_providers(
|
||||
state: State<'_, AppState>,
|
||||
copilot_state: State<'_, CopilotAuthState>,
|
||||
app_type: AppType,
|
||||
proxy_targets_only: bool,
|
||||
) -> Result<Vec<(String, StreamCheckResult)>, AppError> {
|
||||
@@ -67,18 +86,41 @@ pub async fn stream_check_all_providers(
|
||||
}
|
||||
}
|
||||
|
||||
let result = StreamCheckService::check_with_retry(&app_type, &provider, &config)
|
||||
.await
|
||||
.unwrap_or_else(|e| StreamCheckResult {
|
||||
status: HealthStatus::Failed,
|
||||
success: false,
|
||||
message: e.to_string(),
|
||||
response_time_ms: None,
|
||||
http_status: None,
|
||||
model_used: String::new(),
|
||||
tested_at: chrono::Utc::now().timestamp(),
|
||||
retry_count: 0,
|
||||
});
|
||||
let auth_override = resolve_copilot_auth_override(&provider, &copilot_state).await?;
|
||||
let claude_api_format_override = resolve_claude_api_format_override(
|
||||
&app_type,
|
||||
&provider,
|
||||
&config,
|
||||
&copilot_state,
|
||||
auth_override.as_ref(),
|
||||
)
|
||||
.await
|
||||
.unwrap_or_else(|e| {
|
||||
log::warn!(
|
||||
"[StreamCheck] Failed to resolve Claude API format override for {}: {}",
|
||||
provider.id,
|
||||
e
|
||||
);
|
||||
None
|
||||
});
|
||||
let result = StreamCheckService::check_with_retry(
|
||||
&app_type,
|
||||
&provider,
|
||||
&config,
|
||||
auth_override,
|
||||
claude_api_format_override,
|
||||
)
|
||||
.await
|
||||
.unwrap_or_else(|e| StreamCheckResult {
|
||||
status: HealthStatus::Failed,
|
||||
success: false,
|
||||
message: e.to_string(),
|
||||
response_time_ms: None,
|
||||
http_status: None,
|
||||
model_used: String::new(),
|
||||
tested_at: chrono::Utc::now().timestamp(),
|
||||
retry_count: 0,
|
||||
});
|
||||
|
||||
let _ = state
|
||||
.db
|
||||
@@ -104,3 +146,94 @@ pub fn save_stream_check_config(
|
||||
) -> Result<(), AppError> {
|
||||
state.db.save_stream_check_config(&config)
|
||||
}
|
||||
|
||||
async fn resolve_copilot_auth_override(
|
||||
provider: &crate::provider::Provider,
|
||||
copilot_state: &State<'_, CopilotAuthState>,
|
||||
) -> Result<Option<crate::proxy::providers::AuthInfo>, AppError> {
|
||||
let is_copilot = provider
|
||||
.meta
|
||||
.as_ref()
|
||||
.and_then(|meta| meta.provider_type.as_deref())
|
||||
== Some("github_copilot")
|
||||
|| provider
|
||||
.settings_config
|
||||
.pointer("/env/ANTHROPIC_BASE_URL")
|
||||
.and_then(|value| value.as_str())
|
||||
.map(|url| url.contains("githubcopilot.com"))
|
||||
.unwrap_or(false);
|
||||
|
||||
if !is_copilot {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let auth_manager = copilot_state.0.read().await;
|
||||
let account_id = provider
|
||||
.meta
|
||||
.as_ref()
|
||||
.and_then(|meta| meta.github_account_id.clone());
|
||||
|
||||
let token = match account_id.as_deref() {
|
||||
Some(id) => auth_manager
|
||||
.get_valid_token_for_account(id)
|
||||
.await
|
||||
.map_err(|e| AppError::Message(format!("GitHub Copilot 认证失败: {e}")))?,
|
||||
None => auth_manager
|
||||
.get_valid_token()
|
||||
.await
|
||||
.map_err(|e| AppError::Message(format!("GitHub Copilot 认证失败: {e}")))?,
|
||||
};
|
||||
|
||||
Ok(Some(crate::proxy::providers::AuthInfo::new(
|
||||
token,
|
||||
crate::proxy::providers::AuthStrategy::GitHubCopilot,
|
||||
)))
|
||||
}
|
||||
|
||||
async fn resolve_claude_api_format_override(
|
||||
app_type: &AppType,
|
||||
provider: &crate::provider::Provider,
|
||||
config: &StreamCheckConfig,
|
||||
copilot_state: &State<'_, CopilotAuthState>,
|
||||
auth_override: Option<&crate::proxy::providers::AuthInfo>,
|
||||
) -> Result<Option<String>, AppError> {
|
||||
if *app_type != AppType::Claude {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let is_copilot = auth_override
|
||||
.map(|auth| auth.strategy == crate::proxy::providers::AuthStrategy::GitHubCopilot)
|
||||
.unwrap_or(false);
|
||||
if !is_copilot {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let model_id = StreamCheckService::resolve_effective_test_model(app_type, provider, config);
|
||||
let auth_manager = copilot_state.0.read().await;
|
||||
let account_id = provider
|
||||
.meta
|
||||
.as_ref()
|
||||
.and_then(|meta| meta.managed_account_id_for("github_copilot"));
|
||||
|
||||
let vendor_result = match account_id.as_deref() {
|
||||
Some(id) => {
|
||||
auth_manager
|
||||
.get_model_vendor_for_account(id, &model_id)
|
||||
.await
|
||||
}
|
||||
None => auth_manager.get_model_vendor(&model_id).await,
|
||||
};
|
||||
|
||||
let api_format = match vendor_result {
|
||||
Ok(Some(vendor)) if vendor.eq_ignore_ascii_case("openai") => "openai_responses",
|
||||
Ok(Some(_)) | Ok(None) => "openai_chat",
|
||||
Err(err) => {
|
||||
log::warn!(
|
||||
"[StreamCheck] Failed to resolve Copilot model vendor for {model_id}: {err}. Falling back to chat/completions"
|
||||
);
|
||||
"openai_chat"
|
||||
}
|
||||
};
|
||||
|
||||
Ok(Some(api_format.to_string()))
|
||||
}
|
||||
|
||||
@@ -7,6 +7,12 @@ use crate::error::AppError;
|
||||
use rusqlite::params;
|
||||
|
||||
impl Database {
|
||||
const LEGACY_COMMON_CONFIG_MIGRATED_KEY: &'static str = "common_config_legacy_migrated_v1";
|
||||
|
||||
fn config_snippet_cleared_key(app_type: &str) -> String {
|
||||
format!("common_config_{app_type}_cleared")
|
||||
}
|
||||
|
||||
/// 获取设置值
|
||||
pub fn get_setting(&self, key: &str) -> Result<Option<String>, AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
@@ -45,6 +51,60 @@ impl Database {
|
||||
self.get_setting(&format!("common_config_{app_type}"))
|
||||
}
|
||||
|
||||
/// 检查通用配置片段是否被用户显式清空
|
||||
pub fn is_config_snippet_cleared(&self, app_type: &str) -> Result<bool, AppError> {
|
||||
Ok(self
|
||||
.get_setting(&Self::config_snippet_cleared_key(app_type))?
|
||||
.as_deref()
|
||||
== Some("true"))
|
||||
}
|
||||
|
||||
/// 设置通用配置片段是否被显式清空
|
||||
pub fn set_config_snippet_cleared(
|
||||
&self,
|
||||
app_type: &str,
|
||||
cleared: bool,
|
||||
) -> Result<(), AppError> {
|
||||
let key = Self::config_snippet_cleared_key(app_type);
|
||||
if cleared {
|
||||
self.set_setting(&key, "true")
|
||||
} else {
|
||||
let conn = lock_conn!(self.conn);
|
||||
conn.execute("DELETE FROM settings WHERE key = ?1", params![key])
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// 当前是否允许从 live 配置自动抽取通用配置片段
|
||||
pub fn should_auto_extract_config_snippet(&self, app_type: &str) -> Result<bool, AppError> {
|
||||
Ok(self.get_config_snippet(app_type)?.is_none()
|
||||
&& !self.is_config_snippet_cleared(app_type)?)
|
||||
}
|
||||
|
||||
/// 检查历史通用配置迁移是否已经执行过
|
||||
pub fn is_legacy_common_config_migrated(&self) -> Result<bool, AppError> {
|
||||
Ok(self
|
||||
.get_setting(Self::LEGACY_COMMON_CONFIG_MIGRATED_KEY)?
|
||||
.as_deref()
|
||||
== Some("true"))
|
||||
}
|
||||
|
||||
/// 标记历史通用配置迁移已经执行完成
|
||||
pub fn set_legacy_common_config_migrated(&self, migrated: bool) -> Result<(), AppError> {
|
||||
if migrated {
|
||||
self.set_setting(Self::LEGACY_COMMON_CONFIG_MIGRATED_KEY, "true")
|
||||
} else {
|
||||
let conn = lock_conn!(self.conn);
|
||||
conn.execute(
|
||||
"DELETE FROM settings WHERE key = ?1",
|
||||
params![Self::LEGACY_COMMON_CONFIG_MIGRATED_KEY],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// 设置通用配置片段
|
||||
pub fn set_config_snippet(
|
||||
&self,
|
||||
|
||||
@@ -4,7 +4,14 @@
|
||||
|
||||
use super::{lock_conn, Database, SCHEMA_VERSION};
|
||||
use crate::error::AppError;
|
||||
use rusqlite::Connection;
|
||||
use rusqlite::{params, Connection};
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct LegacySkillMigrationRow {
|
||||
directory: String,
|
||||
app_type: String,
|
||||
}
|
||||
|
||||
impl Database {
|
||||
/// 创建所有数据库表
|
||||
@@ -382,7 +389,7 @@ impl Database {
|
||||
Self::set_user_version(conn, 5)?;
|
||||
}
|
||||
5 => {
|
||||
log::info!("迁移数据库从 v5 到 v6(使用量聚合表)");
|
||||
log::info!("迁移数据库从 v5 到 v6(使用量聚合表 + Copilot 模板类型统一)");
|
||||
Self::migrate_v5_to_v6(conn)?;
|
||||
Self::set_user_version(conn, 6)?;
|
||||
}
|
||||
@@ -846,12 +853,31 @@ impl Database {
|
||||
|
||||
log::info!("开始迁移 skills 表到 v3 结构(统一管理架构)...");
|
||||
|
||||
// 1. 备份旧数据(用于日志)
|
||||
// 1. 备份旧数据(用于日志和后续启动迁移)
|
||||
let old_count: i64 = conn
|
||||
.query_row("SELECT COUNT(*) FROM skills", [], |row| row.get(0))
|
||||
.unwrap_or(0);
|
||||
log::info!("旧 skills 表有 {old_count} 条记录");
|
||||
|
||||
let mut stmt = conn
|
||||
.prepare(
|
||||
"SELECT directory, app_type FROM skills
|
||||
WHERE installed = 1",
|
||||
)
|
||||
.map_err(|e| AppError::Database(format!("查询旧 skills 快照失败: {e}")))?;
|
||||
let snapshot_rows: Vec<LegacySkillMigrationRow> = stmt
|
||||
.query_map([], |row| {
|
||||
Ok(LegacySkillMigrationRow {
|
||||
directory: row.get(0)?,
|
||||
app_type: row.get(1)?,
|
||||
})
|
||||
})
|
||||
.map_err(|e| AppError::Database(format!("读取旧 skills 快照失败: {e}")))?
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(|e| AppError::Database(format!("解析旧 skills 快照失败: {e}")))?;
|
||||
let snapshot_json = serde_json::to_string(&snapshot_rows)
|
||||
.map_err(|e| AppError::Database(format!("序列化旧 skills 快照失败: {e}")))?;
|
||||
|
||||
// 标记:需要在启动后从文件系统扫描并重建 Skills 数据
|
||||
// 说明:v3 结构将 Skills 的 SSOT 迁移到 ~/.cc-switch/skills/,
|
||||
// 旧表只存“安装记录”,无法直接无损迁移到新结构,因此改为启动后扫描 app 目录导入。
|
||||
@@ -859,6 +885,10 @@ impl Database {
|
||||
"INSERT OR REPLACE INTO settings (key, value) VALUES ('skills_ssot_migration_pending', 'true')",
|
||||
[],
|
||||
);
|
||||
let _ = conn.execute(
|
||||
"INSERT OR REPLACE INTO settings (key, value) VALUES ('skills_ssot_migration_snapshot', ?1)",
|
||||
[snapshot_json],
|
||||
);
|
||||
|
||||
// 2. 删除旧表
|
||||
conn.execute("DROP TABLE IF EXISTS skills", [])
|
||||
@@ -940,8 +970,9 @@ impl Database {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// v5 -> v6 迁移:添加使用量日聚合表
|
||||
/// v5 -> v6 迁移:添加使用量日聚合表 + 统一 Copilot 模板类型
|
||||
fn migrate_v5_to_v6(conn: &Connection) -> Result<(), AppError> {
|
||||
// 1. 添加使用量日聚合表
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS usage_daily_rollups (
|
||||
date TEXT NOT NULL,
|
||||
@@ -962,7 +993,55 @@ impl Database {
|
||||
)
|
||||
.map_err(|e| AppError::Database(format!("创建 usage_daily_rollups 表失败: {e}")))?;
|
||||
|
||||
log::info!("v5 -> v6 迁移完成:已添加使用量日聚合表");
|
||||
// 2. 统一 Copilot 模板类型为 github_copilot
|
||||
let mut stmt = conn
|
||||
.prepare("SELECT id, app_type, meta FROM providers")
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
let rows = stmt
|
||||
.query_map([], |row| {
|
||||
Ok((
|
||||
row.get::<_, String>(0)?,
|
||||
row.get::<_, String>(1)?,
|
||||
row.get::<_, String>(2)?,
|
||||
))
|
||||
})
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
let mut updates = Vec::new();
|
||||
for row in rows {
|
||||
let (id, app_type, meta_str) = row.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
if let Ok(mut meta) = serde_json::from_str::<serde_json::Value>(&meta_str) {
|
||||
let mut updated = false;
|
||||
|
||||
if let Some(usage_script) = meta.get_mut("usage_script") {
|
||||
if let Some(template_type) = usage_script.get_mut("template_type") {
|
||||
if template_type == "copilot" {
|
||||
*template_type =
|
||||
serde_json::Value::String("github_copilot".to_string());
|
||||
updated = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if updated {
|
||||
let new_meta_str = serde_json::to_string(&meta)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
updates.push((id, app_type, new_meta_str));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (id, app_type, new_meta) in updates {
|
||||
conn.execute(
|
||||
"UPDATE providers SET meta = ?1 WHERE id = ?2 AND app_type = ?3",
|
||||
params![new_meta, id, app_type],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
}
|
||||
|
||||
log::info!("v5 -> v6 迁移完成:已添加使用量日聚合表,统一 copilot 模板类型");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -980,6 +1059,14 @@ impl Database {
|
||||
"0.50",
|
||||
"6.25",
|
||||
),
|
||||
(
|
||||
"claude-sonnet-4-6-20260217",
|
||||
"Claude Sonnet 4.6",
|
||||
"3",
|
||||
"15",
|
||||
"0.30",
|
||||
"3.75",
|
||||
),
|
||||
// Claude 4.5 系列
|
||||
(
|
||||
"claude-opus-4-5-20251101",
|
||||
|
||||
@@ -296,6 +296,14 @@ fn schema_migration_v4_adds_pricing_model_columns() {
|
||||
let conn = Connection::open_in_memory().expect("open memory db");
|
||||
conn.execute_batch(
|
||||
r#"
|
||||
CREATE TABLE providers (
|
||||
id TEXT NOT NULL,
|
||||
app_type TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
settings_config TEXT NOT NULL DEFAULT '{}',
|
||||
meta TEXT NOT NULL DEFAULT '{}',
|
||||
PRIMARY KEY (id, app_type)
|
||||
);
|
||||
CREATE TABLE proxy_config (app_type TEXT PRIMARY KEY);
|
||||
CREATE TABLE proxy_request_logs (request_id TEXT PRIMARY KEY, model TEXT NOT NULL);
|
||||
CREATE TABLE mcp_servers (
|
||||
@@ -488,6 +496,25 @@ fn migration_from_v3_8_schema_v1_to_current_schema_v3() {
|
||||
matches!(pending.as_deref(), Some("true") | Some("1")),
|
||||
"skills_ssot_migration_pending should be set after v2->v3 migration"
|
||||
);
|
||||
let snapshot: Option<String> = conn
|
||||
.query_row(
|
||||
"SELECT value FROM settings WHERE key = 'skills_ssot_migration_snapshot'",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.ok();
|
||||
let snapshot = snapshot.expect("skills migration snapshot should be recorded");
|
||||
let snapshot_rows: serde_json::Value =
|
||||
serde_json::from_str(&snapshot).expect("parse skills migration snapshot");
|
||||
assert!(
|
||||
snapshot_rows
|
||||
.as_array()
|
||||
.is_some_and(|rows| rows.iter().any(|row| {
|
||||
row.get("directory").and_then(|v| v.as_str()) == Some("demo-skill")
|
||||
&& row.get("app_type").and_then(|v| v.as_str()) == Some("claude")
|
||||
})),
|
||||
"skills migration snapshot should preserve legacy app mapping"
|
||||
);
|
||||
|
||||
// v3.9+ 新增:proxy_config 三行 seed 必须存在(否则 UI 会查不到默认值)
|
||||
let proxy_rows: i64 = conn
|
||||
|
||||
@@ -110,7 +110,7 @@ pub fn import_provider_from_deeplink(
|
||||
let provider_id = provider.id.clone();
|
||||
|
||||
// Use ProviderService to add the provider
|
||||
ProviderService::add(state, app_type.clone(), provider)?;
|
||||
ProviderService::add(state, app_type.clone(), provider, true)?;
|
||||
|
||||
// Add extra endpoints as custom endpoints (skip first one as it's the primary)
|
||||
for ep in all_endpoints.iter().skip(1) {
|
||||
|
||||
+154
-54
@@ -12,6 +12,7 @@ mod error;
|
||||
mod gemini_config;
|
||||
mod gemini_mcp;
|
||||
mod init_status;
|
||||
mod lightweight;
|
||||
mod mcp;
|
||||
mod openclaw_config;
|
||||
mod opencode_config;
|
||||
@@ -25,10 +26,11 @@ mod services;
|
||||
mod session_manager;
|
||||
mod settings;
|
||||
mod store;
|
||||
|
||||
mod tray;
|
||||
mod usage_script;
|
||||
|
||||
pub use app_config::{AppType, McpApps, McpServer, MultiAppConfig};
|
||||
pub use app_config::{AppType, InstalledSkill, McpApps, McpServer, MultiAppConfig, SkillApps};
|
||||
pub use codex_config::{get_codex_auth_path, get_codex_config_path, write_codex_live_atomic};
|
||||
pub use commands::open_provider_terminal;
|
||||
pub use commands::*;
|
||||
@@ -44,6 +46,7 @@ pub use mcp::{
|
||||
};
|
||||
pub use provider::{Provider, ProviderMeta};
|
||||
pub use services::{
|
||||
skill::{migrate_skills_to_ssot, ImportSkillSelection},
|
||||
ConfigService, EndpointLatency, McpService, PromptService, ProviderService, ProxyService,
|
||||
SkillService, SpeedtestService,
|
||||
};
|
||||
@@ -202,6 +205,12 @@ pub fn run() {
|
||||
log::debug!(" arg[{i}]: {}", redact_url_for_log(arg));
|
||||
}
|
||||
|
||||
if crate::lightweight::is_lightweight_mode() {
|
||||
if let Err(e) = crate::lightweight::exit_lightweight_mode(app) {
|
||||
log::error!("退出轻量模式重建窗口失败: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
// Check for deep link URL in args (mainly for Windows/Linux command line)
|
||||
let mut found_deeplink = false;
|
||||
for arg in &args {
|
||||
@@ -560,59 +569,6 @@ pub fn run() {
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Auto-extract common config snippets from live files (when snippet is missing)
|
||||
for app_type in crate::app_config::AppType::all() {
|
||||
// Skip if snippet already exists
|
||||
if app_state
|
||||
.db
|
||||
.get_config_snippet(app_type.as_str())
|
||||
.ok()
|
||||
.flatten()
|
||||
.is_some()
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Try to read the live config file for this app type
|
||||
let settings =
|
||||
match crate::services::provider::ProviderService::read_live_settings(
|
||||
app_type.clone(),
|
||||
) {
|
||||
Ok(s) => s,
|
||||
Err(_) => continue, // No live config file, skip silently
|
||||
};
|
||||
|
||||
// Extract common config (strip provider-specific fields)
|
||||
match crate::services::provider::ProviderService::extract_common_config_snippet_from_settings(
|
||||
app_type.clone(),
|
||||
&settings,
|
||||
) {
|
||||
Ok(snippet) if !snippet.is_empty() && snippet != "{}" => {
|
||||
match app_state
|
||||
.db
|
||||
.set_config_snippet(app_type.as_str(), Some(snippet))
|
||||
{
|
||||
Ok(()) => log::info!(
|
||||
"✓ Auto-extracted common config snippet for {}",
|
||||
app_type.as_str()
|
||||
),
|
||||
Err(e) => log::warn!(
|
||||
"✗ Failed to save config snippet for {}: {e}",
|
||||
app_type.as_str()
|
||||
),
|
||||
}
|
||||
}
|
||||
Ok(_) => log::debug!(
|
||||
"○ Live config for {} has no extractable common fields",
|
||||
app_type.as_str()
|
||||
),
|
||||
Err(e) => log::warn!(
|
||||
"✗ Failed to extract config snippet for {}: {e}",
|
||||
app_type.as_str()
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
// 迁移旧的 app_config_dir 配置到 Store
|
||||
if let Err(e) = app_store::migrate_app_config_dir_from_settings(app.handle()) {
|
||||
log::warn!("迁移 app_config_dir 失败: {e}");
|
||||
@@ -666,6 +622,12 @@ pub fn run() {
|
||||
let urls = event.urls();
|
||||
log::info!("Received {} URL(s)", urls.len());
|
||||
|
||||
if crate::lightweight::is_lightweight_mode() {
|
||||
if let Err(e) = crate::lightweight::exit_lightweight_mode(&app_handle) {
|
||||
log::error!("退出轻量模式重建窗口失败: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
for (i, url) in urls.iter().enumerate() {
|
||||
let url_str = url.as_str();
|
||||
log::debug!(" URL[{i}]: {}", redact_url_for_log(url_str));
|
||||
@@ -741,6 +703,18 @@ pub fn run() {
|
||||
let skill_service = SkillService::new();
|
||||
app.manage(commands::skill::SkillServiceState(Arc::new(skill_service)));
|
||||
|
||||
// 初始化 CopilotAuthManager
|
||||
{
|
||||
use crate::proxy::providers::copilot_auth::CopilotAuthManager;
|
||||
use commands::CopilotAuthState;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
let app_config_dir = crate::config::get_app_config_dir();
|
||||
let copilot_auth_manager = CopilotAuthManager::new(app_config_dir);
|
||||
app.manage(CopilotAuthState(Arc::new(RwLock::new(copilot_auth_manager))));
|
||||
log::info!("✓ CopilotAuthManager initialized");
|
||||
}
|
||||
|
||||
// 初始化全局出站代理 HTTP 客户端
|
||||
{
|
||||
let db = &app.state::<AppState>().db;
|
||||
@@ -797,6 +771,8 @@ pub fn run() {
|
||||
}
|
||||
}
|
||||
|
||||
initialize_common_config_snippets(&state);
|
||||
|
||||
// 检查 settings 表中的代理状态,自动恢复代理服务
|
||||
restore_proxy_state_on_startup(&state).await;
|
||||
|
||||
@@ -855,6 +831,7 @@ pub fn run() {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Ok(())
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
@@ -968,8 +945,11 @@ pub fn run() {
|
||||
commands::restore_env_backup,
|
||||
// Skill management (v3.10.0+ unified)
|
||||
commands::get_installed_skills,
|
||||
commands::get_skill_backups,
|
||||
commands::delete_skill_backup,
|
||||
commands::install_skill_unified,
|
||||
commands::uninstall_skill_unified,
|
||||
commands::restore_skill_backup,
|
||||
commands::toggle_skill_app,
|
||||
commands::scan_unmanaged_skills,
|
||||
commands::import_skills_from_apps,
|
||||
@@ -1041,6 +1021,7 @@ pub fn run() {
|
||||
commands::list_sessions,
|
||||
commands::get_session_messages,
|
||||
commands::delete_session,
|
||||
commands::delete_sessions,
|
||||
commands::launch_session_terminal,
|
||||
commands::get_tool_versions,
|
||||
// Provider terminal
|
||||
@@ -1077,6 +1058,31 @@ pub fn run() {
|
||||
commands::scan_local_proxies,
|
||||
// Window theme control
|
||||
commands::set_window_theme,
|
||||
// Generic managed auth commands
|
||||
commands::auth_start_login,
|
||||
commands::auth_poll_for_account,
|
||||
commands::auth_list_accounts,
|
||||
commands::auth_get_status,
|
||||
commands::auth_remove_account,
|
||||
commands::auth_set_default_account,
|
||||
commands::auth_logout,
|
||||
// Copilot OAuth commands (multi-account support)
|
||||
commands::copilot_start_device_flow,
|
||||
commands::copilot_poll_for_auth,
|
||||
commands::copilot_poll_for_account,
|
||||
commands::copilot_list_accounts,
|
||||
commands::copilot_remove_account,
|
||||
commands::copilot_set_default_account,
|
||||
commands::copilot_get_auth_status,
|
||||
commands::copilot_logout,
|
||||
commands::copilot_is_authenticated,
|
||||
commands::copilot_get_token,
|
||||
commands::copilot_get_token_for_account,
|
||||
commands::copilot_get_models,
|
||||
commands::copilot_get_models_for_account,
|
||||
commands::copilot_get_usage,
|
||||
commands::copilot_get_usage_for_account,
|
||||
// OMO commands
|
||||
commands::read_omo_local_file,
|
||||
commands::get_current_omo_provider_id,
|
||||
commands::disable_current_omo,
|
||||
@@ -1093,6 +1099,10 @@ pub fn run() {
|
||||
commands::delete_daily_memory_file,
|
||||
commands::search_daily_memory_files,
|
||||
commands::open_workspace_directory,
|
||||
// lightweight mode (for testing or low-resource environments)
|
||||
commands::enter_lightweight_mode,
|
||||
commands::exit_lightweight_mode,
|
||||
commands::is_lightweight_mode,
|
||||
]);
|
||||
|
||||
let app = builder
|
||||
@@ -1143,6 +1153,10 @@ pub fn run() {
|
||||
let _ = window.show();
|
||||
let _ = window.set_focus();
|
||||
tray::apply_tray_policy(app_handle, true);
|
||||
} else if crate::lightweight::is_lightweight_mode() {
|
||||
if let Err(e) = crate::lightweight::exit_lightweight_mode(app_handle) {
|
||||
log::error!("退出轻量模式重建窗口失败: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
// 处理通过自定义 URL 协议触发的打开事件(例如 ccswitch://...)
|
||||
@@ -1152,6 +1166,13 @@ pub fn run() {
|
||||
log::info!("RunEvent::Opened with URL: {url_str}");
|
||||
|
||||
if url_str.starts_with("ccswitch://") {
|
||||
if crate::lightweight::is_lightweight_mode() {
|
||||
if let Err(e) = crate::lightweight::exit_lightweight_mode(app_handle)
|
||||
{
|
||||
log::error!("退出轻量模式重建窗口失败: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
// 解析并广播深链接事件,复用与 single_instance 相同的逻辑
|
||||
match crate::deeplink::parse_deeplink_url(&url_str) {
|
||||
Ok(request) => {
|
||||
@@ -1305,6 +1326,85 @@ async fn restore_proxy_state_on_startup(state: &store::AppState) {
|
||||
}
|
||||
}
|
||||
|
||||
fn initialize_common_config_snippets(state: &store::AppState) {
|
||||
// Auto-extract common config snippets from clean live files when snippet is missing.
|
||||
// This must run before proxy takeover is restored on startup, otherwise we'd read
|
||||
// proxy-placeholder configs instead of the user's actual live settings.
|
||||
for app_type in crate::app_config::AppType::all() {
|
||||
if !state
|
||||
.db
|
||||
.should_auto_extract_config_snippet(app_type.as_str())
|
||||
.unwrap_or(false)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
let settings = match crate::services::provider::ProviderService::read_live_settings(
|
||||
app_type.clone(),
|
||||
) {
|
||||
Ok(s) => s,
|
||||
Err(_) => continue,
|
||||
};
|
||||
|
||||
match crate::services::provider::ProviderService::extract_common_config_snippet_from_settings(
|
||||
app_type.clone(),
|
||||
&settings,
|
||||
) {
|
||||
Ok(snippet) if !snippet.is_empty() && snippet != "{}" => {
|
||||
match state.db.set_config_snippet(app_type.as_str(), Some(snippet)) {
|
||||
Ok(()) => {
|
||||
let _ = state.db.set_config_snippet_cleared(app_type.as_str(), false);
|
||||
log::info!(
|
||||
"✓ Auto-extracted common config snippet for {}",
|
||||
app_type.as_str()
|
||||
);
|
||||
}
|
||||
Err(e) => log::warn!(
|
||||
"✗ Failed to save config snippet for {}: {e}",
|
||||
app_type.as_str()
|
||||
),
|
||||
}
|
||||
}
|
||||
Ok(_) => log::debug!(
|
||||
"○ Live config for {} has no extractable common fields",
|
||||
app_type.as_str()
|
||||
),
|
||||
Err(e) => log::warn!(
|
||||
"✗ Failed to extract config snippet for {}: {e}",
|
||||
app_type.as_str()
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
let should_run_legacy_migration = state
|
||||
.db
|
||||
.is_legacy_common_config_migrated()
|
||||
.map(|done| !done)
|
||||
.unwrap_or(true);
|
||||
|
||||
if should_run_legacy_migration {
|
||||
for app_type in [
|
||||
crate::app_config::AppType::Claude,
|
||||
crate::app_config::AppType::Codex,
|
||||
crate::app_config::AppType::Gemini,
|
||||
] {
|
||||
if let Err(e) = crate::services::provider::ProviderService::migrate_legacy_common_config_usage_if_needed(
|
||||
state,
|
||||
app_type.clone(),
|
||||
) {
|
||||
log::warn!(
|
||||
"✗ Failed to migrate legacy common-config usage for {}: {e}",
|
||||
app_type.as_str()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if let Err(e) = state.db.set_legacy_common_config_migrated(true) {
|
||||
log::warn!("✗ Failed to persist legacy common-config migration flag: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 迁移错误对话框辅助函数
|
||||
// ============================================================
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use tauri::Manager;
|
||||
|
||||
static LIGHTWEIGHT_MODE: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
pub fn enter_lightweight_mode(app: &tauri::AppHandle) -> Result<(), String> {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
let _ = window.set_skip_taskbar(true);
|
||||
}
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
crate::tray::apply_tray_policy(app, false);
|
||||
}
|
||||
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
window
|
||||
.destroy()
|
||||
.map_err(|e| format!("销毁主窗口失败: {e}"))?;
|
||||
}
|
||||
// else: already in lightweight mode or window not found, just set the flag
|
||||
|
||||
LIGHTWEIGHT_MODE.store(true, Ordering::Release);
|
||||
crate::tray::refresh_tray_menu(app);
|
||||
log::info!("进入轻量模式");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn exit_lightweight_mode(app: &tauri::AppHandle) -> Result<(), String> {
|
||||
use tauri::WebviewWindowBuilder;
|
||||
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
let _ = window.unminimize();
|
||||
let _ = window.show();
|
||||
let _ = window.set_focus();
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let _ = window.set_skip_taskbar(false);
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
crate::tray::apply_tray_policy(app, true);
|
||||
}
|
||||
LIGHTWEIGHT_MODE.store(false, Ordering::Release);
|
||||
crate::tray::refresh_tray_menu(app);
|
||||
log::info!("退出轻量模式");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let window_config = app
|
||||
.config()
|
||||
.app
|
||||
.windows
|
||||
.iter()
|
||||
.find(|w| w.label == "main")
|
||||
.ok_or("主窗口配置未找到")?;
|
||||
|
||||
WebviewWindowBuilder::from_config(app, window_config)
|
||||
.map_err(|e| format!("加载主窗口配置失败: {e}"))?
|
||||
.visible(true)
|
||||
.build()
|
||||
.map_err(|e| format!("创建主窗口失败: {e}"))?;
|
||||
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
let _ = window.set_focus();
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
let _ = window.set_skip_taskbar(false);
|
||||
}
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
crate::tray::apply_tray_policy(app, true);
|
||||
}
|
||||
|
||||
LIGHTWEIGHT_MODE.store(false, Ordering::Release);
|
||||
crate::tray::refresh_tray_menu(app);
|
||||
log::info!("退出轻量模式");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn is_lightweight_mode() -> bool {
|
||||
LIGHTWEIGHT_MODE.load(Ordering::Acquire)
|
||||
}
|
||||
@@ -8,7 +8,6 @@ use crate::error::AppError;
|
||||
use crate::settings::{effective_backup_retain_count, get_openclaw_override_dir};
|
||||
use chrono::Local;
|
||||
use indexmap::IndexMap;
|
||||
use json_five::parser::{FormatConfiguration, TrailingComma};
|
||||
use json_five::rt::parser::{
|
||||
from_str as rt_from_str, JSONKeyValuePair as RtJSONKeyValuePair,
|
||||
JSONObjectContext as RtJSONObjectContext, JSONText as RtJSONText, JSONValue as RtJSONValue,
|
||||
@@ -294,7 +293,7 @@ impl OpenClawConfigDocument {
|
||||
|
||||
if let Some(existing) = key_value_pairs
|
||||
.iter_mut()
|
||||
.find(|pair| json5_key_name(&pair.key).as_deref() == Some(key))
|
||||
.find(|pair| json5_key_name(&pair.key) == Some(key))
|
||||
{
|
||||
existing.value = new_value;
|
||||
return Ok(());
|
||||
@@ -490,11 +489,11 @@ fn derive_entry_separator(leading_ws: &str) -> String {
|
||||
}
|
||||
|
||||
fn value_to_rt_value(value: &Value, parent_indent: &str) -> Result<RtJSONValue, AppError> {
|
||||
let source = json_five::to_string_formatted(
|
||||
value,
|
||||
FormatConfiguration::with_indent(2, TrailingComma::NONE),
|
||||
)
|
||||
.map_err(|e| AppError::Config(format!("Failed to serialize JSON5 section: {e}")))?;
|
||||
// `json-five` 0.3.1 can panic when pretty-printing nested empty maps/arrays.
|
||||
// Serialize with `serde_json` instead; the resulting JSON is valid JSON5 and
|
||||
// can still be parsed back into the round-trip AST we use for insertion.
|
||||
let source = serde_json::to_string_pretty(value)
|
||||
.map_err(|e| AppError::Config(format!("Failed to serialize JSON section: {e}")))?;
|
||||
|
||||
let adjusted = reindent_json5_block(&source, parent_indent);
|
||||
let text = rt_from_str(&adjusted).map_err(|e| {
|
||||
@@ -1051,4 +1050,37 @@ mod tests {
|
||||
assert!(err.to_string().contains("OpenClaw config changed on disk"));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_last_provider_writes_empty_providers_without_panic() {
|
||||
let source = r#"{
|
||||
models: {
|
||||
mode: 'merge',
|
||||
providers: {
|
||||
'1-copy': {
|
||||
api: 'anthropic-messages',
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
"#;
|
||||
|
||||
with_test_paths(source, |_| {
|
||||
let outcome = remove_provider("1-copy").unwrap();
|
||||
assert!(outcome.backup_path.is_some());
|
||||
|
||||
let config = read_openclaw_config().unwrap();
|
||||
let providers = config
|
||||
.get("models")
|
||||
.and_then(|models| models.get("providers"))
|
||||
.and_then(Value::as_object)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
|
||||
assert!(providers.is_empty());
|
||||
|
||||
let written = fs::read_to_string(get_openclaw_config_path()).unwrap();
|
||||
assert!(written.contains("\"providers\": {}"));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,32 @@ use indexmap::IndexMap;
|
||||
use serde_json::{json, Map, Value};
|
||||
use std::path::PathBuf;
|
||||
|
||||
const STANDARD_OMO_PLUGIN_PREFIXES: [&str; 2] = ["oh-my-openagent", "oh-my-opencode"];
|
||||
const SLIM_OMO_PLUGIN_PREFIXES: [&str; 1] = ["oh-my-opencode-slim"];
|
||||
|
||||
fn matches_plugin_prefix(plugin_name: &str, prefix: &str) -> bool {
|
||||
plugin_name == prefix
|
||||
|| plugin_name
|
||||
.strip_prefix(prefix)
|
||||
.map(|suffix| suffix.starts_with('@'))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn matches_any_plugin_prefix(plugin_name: &str, prefixes: &[&str]) -> bool {
|
||||
prefixes
|
||||
.iter()
|
||||
.any(|prefix| matches_plugin_prefix(plugin_name, prefix))
|
||||
}
|
||||
|
||||
fn canonicalize_plugin_name(plugin_name: &str) -> String {
|
||||
if let Some(suffix) = plugin_name.strip_prefix("oh-my-opencode") {
|
||||
if suffix.is_empty() || suffix.starts_with('@') {
|
||||
return format!("oh-my-openagent{suffix}");
|
||||
}
|
||||
}
|
||||
plugin_name.to_string()
|
||||
}
|
||||
|
||||
pub fn get_opencode_dir() -> PathBuf {
|
||||
if let Some(override_dir) = get_opencode_override_dir() {
|
||||
return override_dir;
|
||||
@@ -140,58 +166,56 @@ pub fn remove_mcp_server(id: &str) -> Result<(), AppError> {
|
||||
|
||||
pub fn add_plugin(plugin_name: &str) -> Result<(), AppError> {
|
||||
let mut config = read_opencode_config()?;
|
||||
let normalized_plugin_name = canonicalize_plugin_name(plugin_name);
|
||||
|
||||
let plugins = config.get_mut("plugin").and_then(|v| v.as_array_mut());
|
||||
|
||||
match plugins {
|
||||
Some(arr) => {
|
||||
// Mutual exclusion: standard OMO and OMO Slim cannot coexist as plugins
|
||||
if plugin_name.starts_with("oh-my-opencode")
|
||||
&& !plugin_name.starts_with("oh-my-opencode-slim")
|
||||
{
|
||||
// Adding standard OMO -> remove all Slim variants
|
||||
arr.retain(|v| {
|
||||
v.as_str()
|
||||
.map(|s| !s.starts_with("oh-my-opencode-slim"))
|
||||
.unwrap_or(true)
|
||||
});
|
||||
} else if plugin_name.starts_with("oh-my-opencode-slim") {
|
||||
// Adding Slim -> remove all standard OMO variants (but keep slim)
|
||||
if matches_any_plugin_prefix(&normalized_plugin_name, &STANDARD_OMO_PLUGIN_PREFIXES) {
|
||||
arr.retain(|v| {
|
||||
v.as_str()
|
||||
.map(|s| {
|
||||
!s.starts_with("oh-my-opencode") || s.starts_with("oh-my-opencode-slim")
|
||||
!matches_any_plugin_prefix(s, &STANDARD_OMO_PLUGIN_PREFIXES)
|
||||
&& !matches_any_plugin_prefix(s, &SLIM_OMO_PLUGIN_PREFIXES)
|
||||
})
|
||||
.unwrap_or(true)
|
||||
});
|
||||
} else if matches_any_plugin_prefix(&normalized_plugin_name, &SLIM_OMO_PLUGIN_PREFIXES)
|
||||
{
|
||||
arr.retain(|v| {
|
||||
v.as_str()
|
||||
.map(|s| {
|
||||
!matches_any_plugin_prefix(s, &STANDARD_OMO_PLUGIN_PREFIXES)
|
||||
&& !matches_any_plugin_prefix(s, &SLIM_OMO_PLUGIN_PREFIXES)
|
||||
})
|
||||
.unwrap_or(true)
|
||||
});
|
||||
}
|
||||
|
||||
let already_exists = arr.iter().any(|v| v.as_str() == Some(plugin_name));
|
||||
let already_exists = arr
|
||||
.iter()
|
||||
.any(|v| v.as_str() == Some(normalized_plugin_name.as_str()));
|
||||
if !already_exists {
|
||||
arr.push(Value::String(plugin_name.to_string()));
|
||||
arr.push(Value::String(normalized_plugin_name));
|
||||
}
|
||||
}
|
||||
None => {
|
||||
config["plugin"] = json!([plugin_name]);
|
||||
config["plugin"] = json!([normalized_plugin_name]);
|
||||
}
|
||||
}
|
||||
|
||||
write_opencode_config(&config)
|
||||
}
|
||||
|
||||
pub fn remove_plugin_by_prefix(prefix: &str) -> Result<(), AppError> {
|
||||
pub fn remove_plugins_by_prefixes(prefixes: &[&str]) -> Result<(), AppError> {
|
||||
let mut config = read_opencode_config()?;
|
||||
|
||||
if let Some(arr) = config.get_mut("plugin").and_then(|v| v.as_array_mut()) {
|
||||
arr.retain(|v| {
|
||||
v.as_str()
|
||||
.map(|s| {
|
||||
if !s.starts_with(prefix) {
|
||||
return true; // Keep: doesn't match prefix at all
|
||||
}
|
||||
let rest = &s[prefix.len()..];
|
||||
rest.starts_with('-')
|
||||
})
|
||||
.map(|s| !matches_any_plugin_prefix(s, prefixes))
|
||||
.unwrap_or(true)
|
||||
});
|
||||
|
||||
|
||||
@@ -191,6 +191,31 @@ pub struct ProviderProxyConfig {
|
||||
pub proxy_password: Option<String>,
|
||||
}
|
||||
|
||||
/// 认证绑定来源
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AuthBindingSource {
|
||||
/// 从 provider 自身配置读取认证信息(默认)
|
||||
#[default]
|
||||
ProviderConfig,
|
||||
/// 使用托管账号认证(如 GitHub Copilot OAuth)
|
||||
ManagedAccount,
|
||||
}
|
||||
|
||||
/// 通用认证绑定
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct AuthBinding {
|
||||
/// 认证来源
|
||||
#[serde(default)]
|
||||
pub source: AuthBindingSource,
|
||||
/// 托管认证供应商标识(如 github_copilot)
|
||||
#[serde(rename = "authProvider", skip_serializing_if = "Option::is_none")]
|
||||
pub auth_provider: Option<String>,
|
||||
/// 托管账号 ID;为空表示跟随该认证供应商的默认账号
|
||||
#[serde(rename = "accountId", skip_serializing_if = "Option::is_none")]
|
||||
pub account_id: Option<String>,
|
||||
}
|
||||
|
||||
/// 供应商元数据
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct ProviderMeta {
|
||||
@@ -242,14 +267,55 @@ pub struct ProviderMeta {
|
||||
/// - "openai_responses": OpenAI Responses API 格式,需要转换
|
||||
#[serde(rename = "apiFormat", skip_serializing_if = "Option::is_none")]
|
||||
pub api_format: Option<String>,
|
||||
/// 通用认证绑定(provider_config / managed_account)
|
||||
///
|
||||
/// 新代码应只写入该字段;githubAccountId 仅保留兼容读取。
|
||||
#[serde(rename = "authBinding", skip_serializing_if = "Option::is_none")]
|
||||
pub auth_binding: Option<AuthBinding>,
|
||||
/// Claude 认证字段名("ANTHROPIC_AUTH_TOKEN" 或 "ANTHROPIC_API_KEY")
|
||||
#[serde(rename = "apiKeyField", skip_serializing_if = "Option::is_none")]
|
||||
pub api_key_field: Option<String>,
|
||||
/// 是否将 base_url 视为完整 API 端点(不拼接 endpoint 路径)
|
||||
#[serde(rename = "isFullUrl", skip_serializing_if = "Option::is_none")]
|
||||
pub is_full_url: Option<bool>,
|
||||
/// Prompt cache key for OpenAI-compatible endpoints.
|
||||
/// When set, injected into converted requests to improve cache hit rate.
|
||||
/// If not set, provider ID is used automatically during format conversion.
|
||||
#[serde(rename = "promptCacheKey", skip_serializing_if = "Option::is_none")]
|
||||
pub prompt_cache_key: Option<String>,
|
||||
/// 累加模式应用中,该 provider 是否已写入 live config。
|
||||
/// `None` 表示旧数据/未知状态,`Some(false)` 表示明确仅存在于数据库中。
|
||||
#[serde(rename = "liveConfigManaged", skip_serializing_if = "Option::is_none")]
|
||||
pub live_config_managed: Option<bool>,
|
||||
/// 供应商类型标识(用于特殊供应商检测)
|
||||
/// - "github_copilot": GitHub Copilot 供应商
|
||||
#[serde(rename = "providerType", skip_serializing_if = "Option::is_none")]
|
||||
pub provider_type: Option<String>,
|
||||
/// GitHub Copilot 关联账号 ID(仅 github_copilot 供应商使用)
|
||||
/// 用于多账号支持,关联到特定的 GitHub 账号
|
||||
#[serde(rename = "githubAccountId", skip_serializing_if = "Option::is_none")]
|
||||
pub github_account_id: Option<String>,
|
||||
}
|
||||
|
||||
impl ProviderMeta {
|
||||
/// 解析指定托管认证供应商绑定的账号 ID。
|
||||
///
|
||||
/// 新版优先读取 authBinding,旧版继续兼容 githubAccountId。
|
||||
pub fn managed_account_id_for(&self, auth_provider: &str) -> Option<String> {
|
||||
if let Some(binding) = self.auth_binding.as_ref() {
|
||||
if binding.source == AuthBindingSource::ManagedAccount
|
||||
&& binding.auth_provider.as_deref() == Some(auth_provider)
|
||||
{
|
||||
return binding.account_id.clone();
|
||||
}
|
||||
}
|
||||
|
||||
if auth_provider == "github_copilot" {
|
||||
return self.github_account_id.clone();
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl ProviderManager {
|
||||
|
||||
@@ -68,7 +68,6 @@ pub enum ProxyError {
|
||||
StreamIdleTimeout(u64),
|
||||
|
||||
/// 认证错误
|
||||
#[allow(dead_code)]
|
||||
#[error("认证失败: {0}")]
|
||||
AuthError(String),
|
||||
|
||||
|
||||
@@ -2,15 +2,12 @@
|
||||
//!
|
||||
//! 处理故障转移成功后的供应商切换逻辑,包括:
|
||||
//! - 去重控制(避免多个请求同时触发)
|
||||
//! - 数据库更新
|
||||
//! - 托盘菜单更新
|
||||
//! - 前端事件发射
|
||||
//! - Live 备份更新
|
||||
|
||||
use crate::database::Database;
|
||||
use crate::error::AppError;
|
||||
use std::collections::HashSet;
|
||||
use std::str::FromStr;
|
||||
use std::sync::Arc;
|
||||
use tauri::{Emitter, Manager};
|
||||
use tokio::sync::RwLock;
|
||||
@@ -98,30 +95,21 @@ impl FailoverSwitchManager {
|
||||
|
||||
log::info!("[FO-001] 切换: {app_type} → {provider_name}");
|
||||
|
||||
// 1. 更新数据库 is_current
|
||||
self.db.set_current_provider(app_type, provider_id)?;
|
||||
let mut switched = false;
|
||||
|
||||
// 2. 更新本地 settings(设备级)
|
||||
let app_type_enum = crate::app_config::AppType::from_str(app_type)
|
||||
.map_err(|_| AppError::Message(format!("无效的应用类型: {app_type}")))?;
|
||||
crate::settings::set_current_provider(&app_type_enum, Some(provider_id))?;
|
||||
|
||||
// 3. 更新托盘菜单和发射事件
|
||||
if let Some(app) = app_handle {
|
||||
// 更新托盘菜单
|
||||
if let Some(app_state) = app.try_state::<crate::store::AppState>() {
|
||||
// 更新 Live 备份(确保代理停止时恢复正确配置)
|
||||
if let Ok(Some(provider)) = self.db.get_provider_by_id(provider_id, app_type) {
|
||||
if let Err(e) = app_state
|
||||
.proxy_service
|
||||
.update_live_backup_from_provider(app_type, &provider)
|
||||
.await
|
||||
{
|
||||
log::warn!("[FO-003] Live 备份更新失败: {e}");
|
||||
}
|
||||
switched = app_state
|
||||
.proxy_service
|
||||
.hot_switch_provider(app_type, provider_id)
|
||||
.await
|
||||
.map_err(AppError::Message)?
|
||||
.logical_target_changed;
|
||||
|
||||
if !switched {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
// 重建托盘菜单
|
||||
if let Ok(new_menu) = crate::tray::create_tray_menu(app, app_state.inner()) {
|
||||
if let Some(tray) = app.tray_by_id("main") {
|
||||
if let Err(e) = tray.set_menu(Some(new_menu)) {
|
||||
@@ -142,6 +130,6 @@ impl FailoverSwitchManager {
|
||||
}
|
||||
}
|
||||
|
||||
Ok(true)
|
||||
Ok(switched)
|
||||
}
|
||||
}
|
||||
|
||||
+631
-142
@@ -2,13 +2,14 @@
|
||||
//!
|
||||
//! 负责将请求转发到上游Provider,支持故障转移
|
||||
|
||||
use super::hyper_client::ProxyResponse;
|
||||
use super::{
|
||||
body_filter::filter_private_params_with_whitelist,
|
||||
error::*,
|
||||
failover_switch::FailoverSwitchManager,
|
||||
log_codes::fwd as log_fwd,
|
||||
provider_router::ProviderRouter,
|
||||
providers::{get_adapter, ProviderAdapter, ProviderType},
|
||||
providers::{get_adapter, AuthInfo, AuthStrategy, ProviderAdapter, ProviderType},
|
||||
thinking_budget_rectifier::{rectify_thinking_budget, should_rectify_thinking_budget},
|
||||
thinking_rectifier::{
|
||||
normalize_thinking_type, rectify_anthropic_request, should_rectify_thinking_signature,
|
||||
@@ -16,68 +17,19 @@ use super::{
|
||||
types::{OptimizerConfig, ProxyStatus, RectifierConfig},
|
||||
ProxyError,
|
||||
};
|
||||
use crate::commands::CopilotAuthState;
|
||||
use crate::proxy::providers::copilot_auth::CopilotAuthManager;
|
||||
use crate::{app_config::AppType, provider::Provider};
|
||||
use reqwest::Response;
|
||||
use http::Extensions;
|
||||
use serde_json::Value;
|
||||
use std::sync::Arc;
|
||||
use tauri::Manager;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
/// Headers 黑名单 - 不透传到上游的 Headers
|
||||
///
|
||||
/// 精简版黑名单,只过滤必须覆盖或可能导致问题的 header
|
||||
/// 参考成功透传的请求,保留更多原始 header
|
||||
///
|
||||
/// 注意:客户端 IP 类(x-forwarded-for, x-real-ip)默认透传
|
||||
const HEADER_BLACKLIST: &[&str] = &[
|
||||
// 认证类(会被覆盖)
|
||||
"authorization",
|
||||
"x-api-key",
|
||||
"x-goog-api-key",
|
||||
// 连接类(由 HTTP 客户端管理)
|
||||
"host",
|
||||
"content-length",
|
||||
"transfer-encoding",
|
||||
// 编码类(会被覆盖为 identity)
|
||||
"accept-encoding",
|
||||
// 代理转发类(保留 x-forwarded-for 和 x-real-ip)
|
||||
"x-forwarded-host",
|
||||
"x-forwarded-port",
|
||||
"x-forwarded-proto",
|
||||
"forwarded",
|
||||
// CDN/云服务商特定头
|
||||
"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",
|
||||
// anthropic 特定头单独处理,避免重复
|
||||
"anthropic-beta",
|
||||
"anthropic-version",
|
||||
// 客户端 IP 单独处理(默认透传)
|
||||
"x-forwarded-for",
|
||||
"x-real-ip",
|
||||
];
|
||||
|
||||
pub struct ForwardResult {
|
||||
pub response: Response,
|
||||
pub response: ProxyResponse,
|
||||
pub provider: Provider,
|
||||
pub claude_api_format: Option<String>,
|
||||
}
|
||||
|
||||
pub struct ForwardError {
|
||||
@@ -146,6 +98,7 @@ impl RequestForwarder {
|
||||
endpoint: &str,
|
||||
body: Value,
|
||||
headers: axum::http::HeaderMap,
|
||||
extensions: Extensions,
|
||||
providers: Vec<Provider>,
|
||||
) -> Result<ForwardResult, ForwardError> {
|
||||
// 获取适配器
|
||||
@@ -222,11 +175,12 @@ impl RequestForwarder {
|
||||
endpoint,
|
||||
&provider_body,
|
||||
&headers,
|
||||
&extensions,
|
||||
adapter.as_ref(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(response) => {
|
||||
Ok((response, claude_api_format)) => {
|
||||
// 成功:记录成功并更新熔断器
|
||||
let _ = self
|
||||
.router
|
||||
@@ -280,6 +234,7 @@ impl RequestForwarder {
|
||||
return Ok(ForwardResult {
|
||||
response,
|
||||
provider: provider.clone(),
|
||||
claude_api_format,
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -350,11 +305,12 @@ impl RequestForwarder {
|
||||
endpoint,
|
||||
&provider_body,
|
||||
&headers,
|
||||
&extensions,
|
||||
adapter.as_ref(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(response) => {
|
||||
Ok((response, claude_api_format)) => {
|
||||
log::info!("[{app_type_str}] [RECT-002] 整流重试成功");
|
||||
// 记录成功
|
||||
let _ = self
|
||||
@@ -413,6 +369,7 @@ impl RequestForwarder {
|
||||
return Ok(ForwardResult {
|
||||
response,
|
||||
provider: provider.clone(),
|
||||
claude_api_format,
|
||||
});
|
||||
}
|
||||
Err(retry_err) => {
|
||||
@@ -547,11 +504,12 @@ impl RequestForwarder {
|
||||
endpoint,
|
||||
&provider_body,
|
||||
&headers,
|
||||
&extensions,
|
||||
adapter.as_ref(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(response) => {
|
||||
Ok((response, claude_api_format)) => {
|
||||
log::info!("[{app_type_str}] [RECT-011] budget 整流重试成功");
|
||||
let _ = self
|
||||
.router
|
||||
@@ -603,6 +561,7 @@ impl RequestForwarder {
|
||||
return Ok(ForwardResult {
|
||||
response,
|
||||
provider: provider.clone(),
|
||||
claude_api_format,
|
||||
});
|
||||
}
|
||||
Err(retry_err) => {
|
||||
@@ -784,29 +743,17 @@ impl RequestForwarder {
|
||||
endpoint: &str,
|
||||
body: &Value,
|
||||
headers: &axum::http::HeaderMap,
|
||||
extensions: &Extensions,
|
||||
adapter: &dyn ProviderAdapter,
|
||||
) -> Result<Response, ProxyError> {
|
||||
) -> Result<(ProxyResponse, Option<String>), ProxyError> {
|
||||
// 使用适配器提取 base_url
|
||||
let base_url = adapter.extract_base_url(provider)?;
|
||||
|
||||
// 检查是否需要格式转换
|
||||
let needs_transform = adapter.needs_transform(provider);
|
||||
|
||||
let effective_endpoint =
|
||||
if needs_transform && adapter.name() == "Claude" && endpoint == "/v1/messages" {
|
||||
// 根据 api_format 选择目标端点
|
||||
let api_format = super::providers::get_claude_api_format(provider);
|
||||
if api_format == "openai_responses" {
|
||||
"/v1/responses"
|
||||
} else {
|
||||
"/v1/chat/completions"
|
||||
}
|
||||
} else {
|
||||
endpoint
|
||||
};
|
||||
|
||||
// 使用适配器构建 URL
|
||||
let url = adapter.build_url(&base_url, effective_endpoint);
|
||||
let is_full_url = provider
|
||||
.meta
|
||||
.as_ref()
|
||||
.and_then(|meta| meta.is_full_url)
|
||||
.unwrap_or(false);
|
||||
|
||||
// 应用模型映射(独立于格式转换)
|
||||
let (mapped_body, _original_model, _mapped_model) =
|
||||
@@ -815,9 +762,61 @@ impl RequestForwarder {
|
||||
// 与 CCH 对齐:请求前不做 thinking 主动改写(仅保留兼容入口)
|
||||
let mapped_body = normalize_thinking_type(mapped_body);
|
||||
|
||||
// 确定有效端点
|
||||
// GitHub Copilot API 使用 /chat/completions(无 /v1 前缀)
|
||||
let is_copilot = provider
|
||||
.meta
|
||||
.as_ref()
|
||||
.and_then(|m| m.provider_type.as_deref())
|
||||
== Some("github_copilot")
|
||||
|| base_url.contains("githubcopilot.com");
|
||||
let resolved_claude_api_format = if adapter.name() == "Claude" {
|
||||
Some(
|
||||
self.resolve_claude_api_format(provider, &mapped_body, is_copilot)
|
||||
.await,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let needs_transform = match resolved_claude_api_format.as_deref() {
|
||||
Some(api_format) => super::providers::claude_api_format_needs_transform(api_format),
|
||||
None => adapter.needs_transform(provider),
|
||||
};
|
||||
let (effective_endpoint, passthrough_query) =
|
||||
if needs_transform && adapter.name() == "Claude" {
|
||||
let api_format = resolved_claude_api_format
|
||||
.as_deref()
|
||||
.unwrap_or_else(|| super::providers::get_claude_api_format(provider));
|
||||
rewrite_claude_transform_endpoint(endpoint, api_format, is_copilot)
|
||||
} else {
|
||||
(
|
||||
endpoint.to_string(),
|
||||
split_endpoint_and_query(endpoint)
|
||||
.1
|
||||
.map(ToString::to_string),
|
||||
)
|
||||
};
|
||||
|
||||
let url = if is_full_url {
|
||||
append_query_to_full_url(&base_url, passthrough_query.as_deref())
|
||||
} else {
|
||||
adapter.build_url(&base_url, &effective_endpoint)
|
||||
};
|
||||
|
||||
// 转换请求体(如果需要)
|
||||
let request_body = if needs_transform {
|
||||
adapter.transform_request(mapped_body, provider)?
|
||||
if adapter.name() == "Claude" {
|
||||
let api_format = resolved_claude_api_format
|
||||
.as_deref()
|
||||
.unwrap_or_else(|| super::providers::get_claude_api_format(provider));
|
||||
super::providers::transform_claude_request_for_api_format(
|
||||
mapped_body,
|
||||
provider,
|
||||
api_format,
|
||||
)?
|
||||
} else {
|
||||
adapter.transform_request(mapped_body, provider)?
|
||||
}
|
||||
} else {
|
||||
mapped_body
|
||||
};
|
||||
@@ -825,83 +824,266 @@ impl RequestForwarder {
|
||||
// 过滤私有参数(以 `_` 开头的字段),防止内部信息泄露到上游
|
||||
// 默认使用空白名单,过滤所有 _ 前缀字段
|
||||
let filtered_body = filter_private_params_with_whitelist(request_body, &[]);
|
||||
let force_identity_encoding = needs_transform
|
||||
|| should_force_identity_encoding(&effective_endpoint, &filtered_body, headers);
|
||||
|
||||
// 获取 HTTP 客户端:优先使用供应商单独代理配置,否则使用全局客户端
|
||||
let proxy_config = provider.meta.as_ref().and_then(|m| m.proxy_config.as_ref());
|
||||
let client = super::http_client::get_for_provider(proxy_config);
|
||||
let mut request = client.post(&url);
|
||||
// 获取认证头(提前准备,用于内联替换)
|
||||
let auth_headers = if let Some(mut auth) = adapter.extract_auth(provider) {
|
||||
// GitHub Copilot 特殊处理:从 CopilotAuthManager 获取真实 token
|
||||
if auth.strategy == AuthStrategy::GitHubCopilot {
|
||||
if let Some(app_handle) = &self.app_handle {
|
||||
let copilot_state = app_handle.state::<CopilotAuthState>();
|
||||
let copilot_auth: tokio::sync::RwLockReadGuard<'_, CopilotAuthManager> =
|
||||
copilot_state.0.read().await;
|
||||
|
||||
// 只有当 timeout > 0 时才设置请求超时
|
||||
// Duration::ZERO 在 reqwest 中表示"立刻超时"而不是"禁用超时"
|
||||
// 故障转移关闭时会传入 0,此时应该使用 client 的默认超时(600秒)
|
||||
if !self.non_streaming_timeout.is_zero() {
|
||||
request = request.timeout(self.non_streaming_timeout);
|
||||
}
|
||||
// 从 provider.meta 获取关联的 GitHub 账号 ID(多账号支持)
|
||||
let account_id = provider
|
||||
.meta
|
||||
.as_ref()
|
||||
.and_then(|m| m.managed_account_id_for("github_copilot"));
|
||||
|
||||
// 过滤黑名单 Headers,保护隐私并避免冲突
|
||||
for (key, value) in headers {
|
||||
if HEADER_BLACKLIST
|
||||
.iter()
|
||||
.any(|h| key.as_str().eq_ignore_ascii_case(h))
|
||||
{
|
||||
continue;
|
||||
// 根据账号 ID 获取对应 token(向后兼容:无账号 ID 时使用第一个账号)
|
||||
let token_result = match &account_id {
|
||||
Some(id) => {
|
||||
log::debug!("[Copilot] 使用指定账号 {id} 获取 token");
|
||||
copilot_auth.get_valid_token_for_account(id).await
|
||||
}
|
||||
None => {
|
||||
log::debug!("[Copilot] 使用默认账号获取 token");
|
||||
copilot_auth.get_valid_token().await
|
||||
}
|
||||
};
|
||||
|
||||
match token_result {
|
||||
Ok(token) => {
|
||||
auth = AuthInfo::new(token, AuthStrategy::GitHubCopilot);
|
||||
log::debug!(
|
||||
"[Copilot] 成功获取 Copilot token (account={})",
|
||||
account_id.as_deref().unwrap_or("default")
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!(
|
||||
"[Copilot] 获取 Copilot token 失败 (account={}): {e}",
|
||||
account_id.as_deref().unwrap_or("default")
|
||||
);
|
||||
return Err(ProxyError::AuthError(format!(
|
||||
"GitHub Copilot 认证失败: {e}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
log::error!("[Copilot] AppHandle 不可用");
|
||||
return Err(ProxyError::AuthError(
|
||||
"GitHub Copilot 认证不可用(无 AppHandle)".to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
request = request.header(key, value);
|
||||
}
|
||||
adapter.get_auth_headers(&auth)
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
|
||||
// 处理 anthropic-beta Header(仅 Claude)
|
||||
// 关键:确保包含 claude-code-20250219 标记,这是上游服务验证请求来源的依据
|
||||
// 如果客户端发送的 beta 标记中没有包含 claude-code-20250219,需要补充
|
||||
if adapter.name() == "Claude" {
|
||||
// Copilot 指纹头名(由 get_auth_headers 注入,需在原始头中去重)
|
||||
let copilot_fingerprint_headers: &[&str] = if is_copilot {
|
||||
&[
|
||||
"user-agent",
|
||||
"editor-version",
|
||||
"editor-plugin-version",
|
||||
"copilot-integration-id",
|
||||
"x-github-api-version",
|
||||
"openai-intent",
|
||||
]
|
||||
} else {
|
||||
&[]
|
||||
};
|
||||
|
||||
// 预计算上游 host 值(用于在原位替换 host header)
|
||||
let upstream_host = url
|
||||
.parse::<http::Uri>()
|
||||
.ok()
|
||||
.and_then(|u| u.authority().map(|a| a.to_string()));
|
||||
|
||||
// 预计算 anthropic-beta 值(仅 Claude)
|
||||
let anthropic_beta_value = if adapter.name() == "Claude" {
|
||||
const CLAUDE_CODE_BETA: &str = "claude-code-20250219";
|
||||
let beta_value = if let Some(beta) = headers.get("anthropic-beta") {
|
||||
Some(if let Some(beta) = headers.get("anthropic-beta") {
|
||||
if let Ok(beta_str) = beta.to_str() {
|
||||
// 检查是否已包含 claude-code-20250219
|
||||
if beta_str.contains(CLAUDE_CODE_BETA) {
|
||||
beta_str.to_string()
|
||||
} else {
|
||||
// 补充 claude-code-20250219
|
||||
format!("{CLAUDE_CODE_BETA},{beta_str}")
|
||||
}
|
||||
} else {
|
||||
CLAUDE_CODE_BETA.to_string()
|
||||
}
|
||||
} else {
|
||||
// 如果客户端没有发送,使用默认值
|
||||
CLAUDE_CODE_BETA.to_string()
|
||||
};
|
||||
request = request.header("anthropic-beta", &beta_value);
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// ============================================================
|
||||
// 构建有序 HeaderMap — 内联替换,保持客户端原始顺序
|
||||
// ============================================================
|
||||
let mut ordered_headers = http::HeaderMap::new();
|
||||
let mut saw_auth = false;
|
||||
let mut saw_accept_encoding = false;
|
||||
let mut saw_anthropic_beta = false;
|
||||
let mut saw_anthropic_version = false;
|
||||
|
||||
for (key, value) in headers {
|
||||
let key_str = key.as_str();
|
||||
|
||||
// --- host — 原位替换为上游 host(保持客户端原始位置) ---
|
||||
if key_str.eq_ignore_ascii_case("host") {
|
||||
if let Some(ref host_val) = upstream_host {
|
||||
if let Ok(hv) = http::HeaderValue::from_str(host_val) {
|
||||
ordered_headers.append(key.clone(), hv);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// --- 连接 / 追踪 / CDN 类 — 无条件跳过 ---
|
||||
if matches!(
|
||||
key_str,
|
||||
"content-length"
|
||||
| "transfer-encoding"
|
||||
| "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"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// --- 认证类 — 用 adapter 提供的认证头替换(在原始位置) ---
|
||||
if key_str.eq_ignore_ascii_case("authorization")
|
||||
|| key_str.eq_ignore_ascii_case("x-api-key")
|
||||
|| key_str.eq_ignore_ascii_case("x-goog-api-key")
|
||||
{
|
||||
if !saw_auth {
|
||||
saw_auth = true;
|
||||
for (ah_name, ah_value) in &auth_headers {
|
||||
ordered_headers.append(ah_name.clone(), ah_value.clone());
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// --- accept-encoding — transform / SSE 路径强制 identity,其余保留原值 ---
|
||||
if key_str.eq_ignore_ascii_case("accept-encoding") {
|
||||
if !saw_accept_encoding {
|
||||
saw_accept_encoding = true;
|
||||
if force_identity_encoding {
|
||||
ordered_headers.append(
|
||||
http::header::ACCEPT_ENCODING,
|
||||
http::HeaderValue::from_static("identity"),
|
||||
);
|
||||
} else {
|
||||
ordered_headers.append(key.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// --- anthropic-beta — 用重建值替换(确保含 claude-code 标记) ---
|
||||
if key_str.eq_ignore_ascii_case("anthropic-beta") {
|
||||
if !saw_anthropic_beta {
|
||||
saw_anthropic_beta = true;
|
||||
if let Some(ref beta_val) = anthropic_beta_value {
|
||||
if let Ok(hv) = http::HeaderValue::from_str(beta_val) {
|
||||
ordered_headers.append("anthropic-beta", hv);
|
||||
}
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// --- anthropic-version — 透传客户端值 ---
|
||||
if key_str.eq_ignore_ascii_case("anthropic-version") {
|
||||
saw_anthropic_version = true;
|
||||
ordered_headers.append(key.clone(), value.clone());
|
||||
continue;
|
||||
}
|
||||
|
||||
// --- Copilot 指纹头 — 跳过(由 auth_headers 提供) ---
|
||||
if copilot_fingerprint_headers
|
||||
.iter()
|
||||
.any(|h| key_str.eq_ignore_ascii_case(h))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// --- 默认:透传 ---
|
||||
ordered_headers.append(key.clone(), value.clone());
|
||||
}
|
||||
|
||||
// 客户端 IP 透传(默认开启)
|
||||
if let Some(xff) = headers.get("x-forwarded-for") {
|
||||
if let Ok(xff_str) = xff.to_str() {
|
||||
request = request.header("x-forwarded-for", xff_str);
|
||||
}
|
||||
}
|
||||
if let Some(real_ip) = headers.get("x-real-ip") {
|
||||
if let Ok(real_ip_str) = real_ip.to_str() {
|
||||
request = request.header("x-real-ip", real_ip_str);
|
||||
// 如果原始请求中没有认证头,在末尾追加
|
||||
if !saw_auth && !auth_headers.is_empty() {
|
||||
for (ah_name, ah_value) in &auth_headers {
|
||||
ordered_headers.append(ah_name.clone(), ah_value.clone());
|
||||
}
|
||||
}
|
||||
|
||||
// 禁用压缩,避免 gzip 流式响应解析错误
|
||||
// 参考 CCH: undici 在连接提前关闭时会对不完整的 gzip 流抛出错误
|
||||
request = request.header("accept-encoding", "identity");
|
||||
|
||||
// 使用适配器添加认证头
|
||||
if let Some(auth) = adapter.extract_auth(provider) {
|
||||
request = adapter.add_auth_headers(request, &auth);
|
||||
// transform / SSE 路径在缺失时补 identity;普通透传不主动补 accept-encoding
|
||||
if !saw_accept_encoding && force_identity_encoding {
|
||||
ordered_headers.append(
|
||||
http::header::ACCEPT_ENCODING,
|
||||
http::HeaderValue::from_static("identity"),
|
||||
);
|
||||
}
|
||||
|
||||
// anthropic-version 统一处理(仅 Claude):优先使用客户端的版本号,否则使用默认值
|
||||
// 注意:只设置一次,避免重复
|
||||
if adapter.name() == "Claude" {
|
||||
let version_str = headers
|
||||
.get("anthropic-version")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.unwrap_or("2023-06-01");
|
||||
request = request.header("anthropic-version", version_str);
|
||||
// 如果原始请求中没有 anthropic-beta 且有值需要添加,追加
|
||||
if !saw_anthropic_beta {
|
||||
if let Some(ref beta_val) = anthropic_beta_value {
|
||||
if let Ok(hv) = http::HeaderValue::from_str(beta_val) {
|
||||
ordered_headers.append("anthropic-beta", hv);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// anthropic-version:仅在缺失时补充默认值
|
||||
if adapter.name() == "Claude" && !saw_anthropic_version {
|
||||
ordered_headers.append(
|
||||
"anthropic-version",
|
||||
http::HeaderValue::from_static("2023-06-01"),
|
||||
);
|
||||
}
|
||||
|
||||
// 序列化请求体
|
||||
let body_bytes = serde_json::to_vec(&filtered_body)
|
||||
.map_err(|e| ProxyError::Internal(format!("Failed to serialize request body: {e}")))?;
|
||||
|
||||
// 确保 content-type 存在
|
||||
if !ordered_headers.contains_key(http::header::CONTENT_TYPE) {
|
||||
ordered_headers.insert(
|
||||
http::header::CONTENT_TYPE,
|
||||
http::HeaderValue::from_static("application/json"),
|
||||
);
|
||||
}
|
||||
|
||||
// 输出请求信息日志
|
||||
@@ -919,25 +1101,75 @@ impl RequestForwarder {
|
||||
);
|
||||
}
|
||||
|
||||
// 确定超时
|
||||
let timeout = if self.non_streaming_timeout.is_zero() {
|
||||
std::time::Duration::from_secs(600) // 默认 600 秒
|
||||
} else {
|
||||
self.non_streaming_timeout
|
||||
};
|
||||
|
||||
// 解析上游代理 URL(供应商单独代理 > 全局代理 > 无)
|
||||
let proxy_config = provider.meta.as_ref().and_then(|m| m.proxy_config.as_ref());
|
||||
let upstream_proxy_url: Option<String> = proxy_config
|
||||
.filter(|c| c.enabled)
|
||||
.and_then(super::http_client::build_proxy_url_from_config)
|
||||
.or_else(super::http_client::get_current_proxy_url);
|
||||
|
||||
// SOCKS5 代理不支持 CONNECT 隧道,需要用 reqwest
|
||||
let is_socks_proxy = upstream_proxy_url
|
||||
.as_deref()
|
||||
.map(|u| u.starts_with("socks5"))
|
||||
.unwrap_or(false);
|
||||
|
||||
let uri: http::Uri = url
|
||||
.parse()
|
||||
.map_err(|e| ProxyError::ForwardFailed(format!("Invalid URL '{url}': {e}")))?;
|
||||
|
||||
// 发送请求
|
||||
let response = request.json(&filtered_body).send().await.map_err(|e| {
|
||||
if e.is_timeout() {
|
||||
ProxyError::Timeout(format!("请求超时: {e}"))
|
||||
} else if e.is_connect() {
|
||||
ProxyError::ForwardFailed(format!("连接失败: {e}"))
|
||||
} else {
|
||||
ProxyError::ForwardFailed(e.to_string())
|
||||
let response = if is_socks_proxy {
|
||||
// SOCKS5 代理:只能走 reqwest(不支持 header case 保留)
|
||||
log::debug!("[Forwarder] Using reqwest for SOCKS5 proxy");
|
||||
let client = super::http_client::get_for_provider(proxy_config);
|
||||
let mut request = client.post(&url);
|
||||
if !self.non_streaming_timeout.is_zero() {
|
||||
request = request.timeout(self.non_streaming_timeout);
|
||||
}
|
||||
})?;
|
||||
for (key, value) in &ordered_headers {
|
||||
request = request.header(key, value);
|
||||
}
|
||||
let reqwest_resp = request.body(body_bytes).send().await.map_err(|e| {
|
||||
if e.is_timeout() {
|
||||
ProxyError::Timeout(format!("请求超时: {e}"))
|
||||
} else if e.is_connect() {
|
||||
ProxyError::ForwardFailed(format!("连接失败: {e}"))
|
||||
} else {
|
||||
ProxyError::ForwardFailed(e.to_string())
|
||||
}
|
||||
})?;
|
||||
ProxyResponse::Reqwest(reqwest_resp)
|
||||
} else {
|
||||
// HTTP 代理或直连:走 hyper raw write(保持 header 大小写)
|
||||
// 如果有 HTTP 代理,hyper_client 会用 CONNECT 隧道穿过代理
|
||||
super::hyper_client::send_request(
|
||||
uri,
|
||||
http::Method::POST,
|
||||
ordered_headers,
|
||||
extensions.clone(),
|
||||
body_bytes,
|
||||
timeout,
|
||||
upstream_proxy_url.as_deref(),
|
||||
)
|
||||
.await?
|
||||
};
|
||||
|
||||
// 检查响应状态
|
||||
let status = response.status();
|
||||
|
||||
if status.is_success() {
|
||||
Ok(response)
|
||||
Ok((response, resolved_claude_api_format))
|
||||
} else {
|
||||
let status_code = status.as_u16();
|
||||
let body_text = response.text().await.ok();
|
||||
let body_text = String::from_utf8(response.bytes().await?.to_vec()).ok();
|
||||
|
||||
Err(ProxyError::UpstreamError {
|
||||
status: status_code,
|
||||
@@ -946,6 +1178,68 @@ impl RequestForwarder {
|
||||
}
|
||||
}
|
||||
|
||||
async fn resolve_claude_api_format(
|
||||
&self,
|
||||
provider: &Provider,
|
||||
body: &Value,
|
||||
is_copilot: bool,
|
||||
) -> String {
|
||||
if !is_copilot {
|
||||
return super::providers::get_claude_api_format(provider).to_string();
|
||||
}
|
||||
|
||||
let model = body.get("model").and_then(|value| value.as_str());
|
||||
if let Some(model_id) = model {
|
||||
if self
|
||||
.is_copilot_openai_vendor_model(provider, model_id)
|
||||
.await
|
||||
{
|
||||
return "openai_responses".to_string();
|
||||
}
|
||||
}
|
||||
|
||||
"openai_chat".to_string()
|
||||
}
|
||||
|
||||
async fn is_copilot_openai_vendor_model(&self, provider: &Provider, model_id: &str) -> bool {
|
||||
let Some(app_handle) = &self.app_handle else {
|
||||
log::debug!("[Copilot] AppHandle unavailable, fallback to chat/completions");
|
||||
return false;
|
||||
};
|
||||
|
||||
let copilot_state = app_handle.state::<CopilotAuthState>();
|
||||
let copilot_auth = copilot_state.0.read().await;
|
||||
let account_id = provider
|
||||
.meta
|
||||
.as_ref()
|
||||
.and_then(|m| m.managed_account_id_for("github_copilot"));
|
||||
|
||||
let vendor_result = match account_id.as_deref() {
|
||||
Some(id) => {
|
||||
copilot_auth
|
||||
.get_model_vendor_for_account(id, model_id)
|
||||
.await
|
||||
}
|
||||
None => copilot_auth.get_model_vendor(model_id).await,
|
||||
};
|
||||
|
||||
match vendor_result {
|
||||
Ok(Some(vendor)) => vendor.eq_ignore_ascii_case("openai"),
|
||||
Ok(None) => {
|
||||
log::debug!(
|
||||
"[Copilot] Model vendor unavailable for {model_id}, fallback to chat/completions"
|
||||
);
|
||||
false
|
||||
}
|
||||
Err(err) => {
|
||||
log::warn!(
|
||||
"[Copilot] Failed to resolve model vendor for {model_id}, fallback to chat/completions: {err}"
|
||||
);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn categorize_proxy_error(&self, error: &ProxyError) -> ErrorCategory {
|
||||
match error {
|
||||
// 网络和上游错误:都应该尝试下一个供应商
|
||||
@@ -1092,6 +1386,102 @@ fn extract_json_error_message(body: &Value) -> Option<String> {
|
||||
.find_map(|value| value.as_str().map(ToString::to_string))
|
||||
}
|
||||
|
||||
fn split_endpoint_and_query(endpoint: &str) -> (&str, Option<&str>) {
|
||||
endpoint
|
||||
.split_once('?')
|
||||
.map_or((endpoint, None), |(path, query)| (path, Some(query)))
|
||||
}
|
||||
|
||||
fn strip_beta_query(query: Option<&str>) -> Option<String> {
|
||||
let filtered = query.map(|query| {
|
||||
query
|
||||
.split('&')
|
||||
.filter(|pair| !pair.is_empty() && !pair.starts_with("beta="))
|
||||
.collect::<Vec<_>>()
|
||||
.join("&")
|
||||
});
|
||||
|
||||
match filtered.as_deref() {
|
||||
Some("") | None => None,
|
||||
Some(_) => filtered,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_claude_messages_path(path: &str) -> bool {
|
||||
matches!(path, "/v1/messages" | "/claude/v1/messages")
|
||||
}
|
||||
|
||||
fn rewrite_claude_transform_endpoint(
|
||||
endpoint: &str,
|
||||
api_format: &str,
|
||||
is_copilot: bool,
|
||||
) -> (String, Option<String>) {
|
||||
let (path, query) = split_endpoint_and_query(endpoint);
|
||||
let passthrough_query = if is_claude_messages_path(path) {
|
||||
strip_beta_query(query)
|
||||
} else {
|
||||
query.map(ToString::to_string)
|
||||
};
|
||||
|
||||
if !is_claude_messages_path(path) {
|
||||
return (endpoint.to_string(), passthrough_query);
|
||||
}
|
||||
|
||||
let target_path = if is_copilot && api_format == "openai_responses" {
|
||||
"/v1/responses"
|
||||
} else if is_copilot {
|
||||
"/chat/completions"
|
||||
} else if api_format == "openai_responses" {
|
||||
"/v1/responses"
|
||||
} else {
|
||||
"/v1/chat/completions"
|
||||
};
|
||||
|
||||
let rewritten = match passthrough_query.as_deref() {
|
||||
Some(query) if !query.is_empty() => format!("{target_path}?{query}"),
|
||||
_ => target_path.to_string(),
|
||||
};
|
||||
|
||||
(rewritten, passthrough_query)
|
||||
}
|
||||
|
||||
fn append_query_to_full_url(base_url: &str, query: Option<&str>) -> String {
|
||||
match query {
|
||||
Some(query) if !query.is_empty() => {
|
||||
if base_url.contains('?') {
|
||||
format!("{base_url}&{query}")
|
||||
} else {
|
||||
format!("{base_url}?{query}")
|
||||
}
|
||||
}
|
||||
_ => base_url.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn should_force_identity_encoding(
|
||||
endpoint: &str,
|
||||
body: &Value,
|
||||
headers: &axum::http::HeaderMap,
|
||||
) -> bool {
|
||||
if body
|
||||
.get("stream")
|
||||
.and_then(|value| value.as_bool())
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if endpoint.contains("streamGenerateContent") || endpoint.contains("alt=sse") {
|
||||
return true;
|
||||
}
|
||||
|
||||
headers
|
||||
.get(axum::http::header::ACCEPT)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(|accept| accept.contains("text/event-stream"))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn summarize_text_for_log(text: &str, max_chars: usize) -> String {
|
||||
let normalized = text.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
let trimmed = normalized.trim();
|
||||
@@ -1108,6 +1498,8 @@ fn summarize_text_for_log(text: &str, max_chars: usize) -> String {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use axum::http::header::{HeaderValue, ACCEPT};
|
||||
use axum::http::HeaderMap;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
@@ -1174,4 +1566,101 @@ mod tests {
|
||||
|
||||
assert_eq!(summary, "line1 line2...");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrite_claude_transform_endpoint_strips_beta_for_chat_completions() {
|
||||
let (endpoint, passthrough_query) = rewrite_claude_transform_endpoint(
|
||||
"/v1/messages?beta=true&foo=bar",
|
||||
"openai_chat",
|
||||
false,
|
||||
);
|
||||
|
||||
assert_eq!(endpoint, "/v1/chat/completions?foo=bar");
|
||||
assert_eq!(passthrough_query.as_deref(), Some("foo=bar"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrite_claude_transform_endpoint_strips_beta_for_responses() {
|
||||
let (endpoint, passthrough_query) = rewrite_claude_transform_endpoint(
|
||||
"/claude/v1/messages?beta=true&x-id=1",
|
||||
"openai_responses",
|
||||
false,
|
||||
);
|
||||
|
||||
assert_eq!(endpoint, "/v1/responses?x-id=1");
|
||||
assert_eq!(passthrough_query.as_deref(), Some("x-id=1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrite_claude_transform_endpoint_uses_copilot_path() {
|
||||
let (endpoint, passthrough_query) =
|
||||
rewrite_claude_transform_endpoint("/v1/messages?beta=true&x-id=1", "anthropic", true);
|
||||
|
||||
assert_eq!(endpoint, "/chat/completions?x-id=1");
|
||||
assert_eq!(passthrough_query.as_deref(), Some("x-id=1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrite_claude_transform_endpoint_uses_copilot_responses_path() {
|
||||
let (endpoint, passthrough_query) = rewrite_claude_transform_endpoint(
|
||||
"/v1/messages?beta=true&x-id=1",
|
||||
"openai_responses",
|
||||
true,
|
||||
);
|
||||
|
||||
assert_eq!(endpoint, "/v1/responses?x-id=1");
|
||||
assert_eq!(passthrough_query.as_deref(), Some("x-id=1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn append_query_to_full_url_preserves_existing_query_string() {
|
||||
let url = append_query_to_full_url("https://relay.example/api?foo=bar", Some("x-id=1"));
|
||||
|
||||
assert_eq!(url, "https://relay.example/api?foo=bar&x-id=1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn force_identity_for_stream_flag_requests() {
|
||||
let headers = HeaderMap::new();
|
||||
|
||||
assert!(should_force_identity_encoding(
|
||||
"/v1/responses",
|
||||
&json!({ "stream": true }),
|
||||
&headers
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn force_identity_for_gemini_stream_endpoints() {
|
||||
let headers = HeaderMap::new();
|
||||
|
||||
assert!(should_force_identity_encoding(
|
||||
"/v1beta/models/gemini-2.5-pro:streamGenerateContent?alt=sse",
|
||||
&json!({ "model": "gemini-2.5-pro" }),
|
||||
&headers
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn force_identity_for_sse_accept_header() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(ACCEPT, HeaderValue::from_static("text/event-stream"));
|
||||
|
||||
assert!(should_force_identity_encoding(
|
||||
"/v1/responses",
|
||||
&json!({ "model": "gpt-5" }),
|
||||
&headers
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_streaming_requests_allow_automatic_compression() {
|
||||
let headers = HeaderMap::new();
|
||||
|
||||
assert!(!should_force_identity_encoding(
|
||||
"/v1/responses",
|
||||
&json!({ "model": "gpt-5" }),
|
||||
&headers
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
+112
-29
@@ -18,7 +18,10 @@ use super::{
|
||||
streaming_responses::create_anthropic_sse_stream_from_responses, transform,
|
||||
transform_responses,
|
||||
},
|
||||
response_processor::{create_logged_passthrough_stream, process_response, SseUsageCollector},
|
||||
response_processor::{
|
||||
create_logged_passthrough_stream, process_response, read_decoded_body,
|
||||
strip_entity_headers_for_rebuilt_body, SseUsageCollector,
|
||||
},
|
||||
server::ProxyState,
|
||||
types::*,
|
||||
usage::parser::TokenUsage,
|
||||
@@ -27,6 +30,7 @@ use super::{
|
||||
use crate::app_config::AppType;
|
||||
use axum::{extract::State, http::StatusCode, response::IntoResponse, Json};
|
||||
use bytes::Bytes;
|
||||
use http_body_util::BodyExt;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
// ============================================================================
|
||||
@@ -61,12 +65,28 @@ pub async fn get_status(State(state): State<ProxyState>) -> Result<Json<ProxySta
|
||||
/// - 现在 OpenRouter 已推出 Claude Code 兼容接口,默认不再启用该转换(逻辑保留以备回退)
|
||||
pub async fn handle_messages(
|
||||
State(state): State<ProxyState>,
|
||||
headers: axum::http::HeaderMap,
|
||||
Json(body): Json<Value>,
|
||||
request: axum::extract::Request,
|
||||
) -> Result<axum::response::Response, ProxyError> {
|
||||
let (parts, body) = request.into_parts();
|
||||
let uri = parts.uri;
|
||||
let headers = parts.headers;
|
||||
let extensions = parts.extensions;
|
||||
let body_bytes = body
|
||||
.collect()
|
||||
.await
|
||||
.map_err(|e| ProxyError::Internal(format!("Failed to read request body: {e}")))?
|
||||
.to_bytes();
|
||||
let body: Value = serde_json::from_slice(&body_bytes)
|
||||
.map_err(|e| ProxyError::Internal(format!("Failed to parse request body: {e}")))?;
|
||||
|
||||
let mut ctx =
|
||||
RequestContext::new(&state, &body, &headers, AppType::Claude, "Claude", "claude").await?;
|
||||
|
||||
let endpoint = uri
|
||||
.path_and_query()
|
||||
.map(|path_and_query| path_and_query.as_str())
|
||||
.unwrap_or(uri.path());
|
||||
|
||||
let is_stream = body
|
||||
.get("stream")
|
||||
.and_then(|s| s.as_bool())
|
||||
@@ -77,9 +97,10 @@ pub async fn handle_messages(
|
||||
let result = match forwarder
|
||||
.forward_with_retry(
|
||||
&AppType::Claude,
|
||||
"/v1/messages",
|
||||
endpoint,
|
||||
body.clone(),
|
||||
headers,
|
||||
extensions,
|
||||
ctx.get_providers(),
|
||||
)
|
||||
.await
|
||||
@@ -95,6 +116,11 @@ pub async fn handle_messages(
|
||||
};
|
||||
|
||||
ctx.provider = result.provider;
|
||||
let api_format = result
|
||||
.claude_api_format
|
||||
.as_deref()
|
||||
.unwrap_or_else(|| get_claude_api_format(&ctx.provider))
|
||||
.to_string();
|
||||
let response = result.response;
|
||||
|
||||
// 检查是否需要格式转换(OpenRouter 等中转服务)
|
||||
@@ -103,7 +129,8 @@ pub async fn handle_messages(
|
||||
|
||||
// Claude 特有:格式转换处理
|
||||
if needs_transform {
|
||||
return handle_claude_transform(response, &ctx, &state, &body, is_stream).await;
|
||||
return handle_claude_transform(response, &ctx, &state, &body, is_stream, &api_format)
|
||||
.await;
|
||||
}
|
||||
|
||||
// 通用响应处理(透传模式)
|
||||
@@ -114,14 +141,14 @@ pub async fn handle_messages(
|
||||
///
|
||||
/// 支持 OpenAI Chat Completions 和 Responses API 两种格式的转换
|
||||
async fn handle_claude_transform(
|
||||
response: reqwest::Response,
|
||||
response: super::hyper_client::ProxyResponse,
|
||||
ctx: &RequestContext,
|
||||
state: &ProxyState,
|
||||
_original_body: &Value,
|
||||
is_stream: bool,
|
||||
api_format: &str,
|
||||
) -> Result<axum::response::Response, ProxyError> {
|
||||
let status = response.status();
|
||||
let api_format = get_claude_api_format(&ctx.provider);
|
||||
|
||||
if is_stream {
|
||||
// 根据 api_format 选择流式转换器
|
||||
@@ -199,12 +226,14 @@ async fn handle_claude_transform(
|
||||
}
|
||||
|
||||
// 非流式响应转换 (OpenAI/Responses → Anthropic)
|
||||
let response_headers = response.headers().clone();
|
||||
|
||||
let body_bytes = response.bytes().await.map_err(|e| {
|
||||
log::error!("[Claude] 读取响应体失败: {e}");
|
||||
ProxyError::ForwardFailed(format!("Failed to read response body: {e}"))
|
||||
})?;
|
||||
let body_timeout =
|
||||
if ctx.app_config.auto_failover_enabled && ctx.app_config.non_streaming_timeout > 0 {
|
||||
std::time::Duration::from_secs(ctx.app_config.non_streaming_timeout as u64)
|
||||
} else {
|
||||
std::time::Duration::ZERO
|
||||
};
|
||||
let (mut response_headers, _status, body_bytes) =
|
||||
read_decoded_body(response, ctx.tag, body_timeout).await?;
|
||||
|
||||
let body_str = String::from_utf8_lossy(&body_bytes);
|
||||
|
||||
@@ -257,13 +286,10 @@ async fn handle_claude_transform(
|
||||
|
||||
// 构建响应
|
||||
let mut builder = axum::response::Response::builder().status(status);
|
||||
strip_entity_headers_for_rebuilt_body(&mut response_headers);
|
||||
|
||||
for (key, value) in response_headers.iter() {
|
||||
if key.as_str().to_lowercase() != "content-length"
|
||||
&& key.as_str().to_lowercase() != "transfer-encoding"
|
||||
{
|
||||
builder = builder.header(key, value);
|
||||
}
|
||||
builder = builder.header(key, value);
|
||||
}
|
||||
|
||||
builder = builder.header("content-type", "application/json");
|
||||
@@ -280,6 +306,13 @@ async fn handle_claude_transform(
|
||||
})
|
||||
}
|
||||
|
||||
fn endpoint_with_query(uri: &axum::http::Uri, endpoint: &str) -> String {
|
||||
match uri.query() {
|
||||
Some(query) => format!("{endpoint}?{query}"),
|
||||
None => endpoint.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Codex API 处理器
|
||||
// ============================================================================
|
||||
@@ -287,11 +320,23 @@ async fn handle_claude_transform(
|
||||
/// 处理 /v1/chat/completions 请求(OpenAI Chat Completions API - Codex CLI)
|
||||
pub async fn handle_chat_completions(
|
||||
State(state): State<ProxyState>,
|
||||
headers: axum::http::HeaderMap,
|
||||
Json(body): Json<Value>,
|
||||
request: axum::extract::Request,
|
||||
) -> Result<axum::response::Response, ProxyError> {
|
||||
let (parts, req_body) = request.into_parts();
|
||||
let uri = parts.uri;
|
||||
let 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: Value = serde_json::from_slice(&body_bytes)
|
||||
.map_err(|e| ProxyError::Internal(format!("Failed to parse request body: {e}")))?;
|
||||
|
||||
let mut ctx =
|
||||
RequestContext::new(&state, &body, &headers, AppType::Codex, "Codex", "codex").await?;
|
||||
let endpoint = endpoint_with_query(&uri, "/chat/completions");
|
||||
|
||||
let is_stream = body
|
||||
.get("stream")
|
||||
@@ -302,9 +347,10 @@ pub async fn handle_chat_completions(
|
||||
let result = match forwarder
|
||||
.forward_with_retry(
|
||||
&AppType::Codex,
|
||||
"/chat/completions",
|
||||
&endpoint,
|
||||
body,
|
||||
headers,
|
||||
extensions,
|
||||
ctx.get_providers(),
|
||||
)
|
||||
.await
|
||||
@@ -328,11 +374,23 @@ pub async fn handle_chat_completions(
|
||||
/// 处理 /v1/responses 请求(OpenAI Responses API - Codex CLI 透传)
|
||||
pub async fn handle_responses(
|
||||
State(state): State<ProxyState>,
|
||||
headers: axum::http::HeaderMap,
|
||||
Json(body): Json<Value>,
|
||||
request: axum::extract::Request,
|
||||
) -> Result<axum::response::Response, ProxyError> {
|
||||
let (parts, req_body) = request.into_parts();
|
||||
let uri = parts.uri;
|
||||
let 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: Value = serde_json::from_slice(&body_bytes)
|
||||
.map_err(|e| ProxyError::Internal(format!("Failed to parse request body: {e}")))?;
|
||||
|
||||
let mut ctx =
|
||||
RequestContext::new(&state, &body, &headers, AppType::Codex, "Codex", "codex").await?;
|
||||
let endpoint = endpoint_with_query(&uri, "/responses");
|
||||
|
||||
let is_stream = body
|
||||
.get("stream")
|
||||
@@ -343,9 +401,10 @@ pub async fn handle_responses(
|
||||
let result = match forwarder
|
||||
.forward_with_retry(
|
||||
&AppType::Codex,
|
||||
"/responses",
|
||||
&endpoint,
|
||||
body,
|
||||
headers,
|
||||
extensions,
|
||||
ctx.get_providers(),
|
||||
)
|
||||
.await
|
||||
@@ -369,11 +428,23 @@ pub async fn handle_responses(
|
||||
/// 处理 /v1/responses/compact 请求(OpenAI Responses Compact API - Codex CLI 透传)
|
||||
pub async fn handle_responses_compact(
|
||||
State(state): State<ProxyState>,
|
||||
headers: axum::http::HeaderMap,
|
||||
Json(body): Json<Value>,
|
||||
request: axum::extract::Request,
|
||||
) -> Result<axum::response::Response, ProxyError> {
|
||||
let (parts, req_body) = request.into_parts();
|
||||
let uri = parts.uri;
|
||||
let 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: Value = serde_json::from_slice(&body_bytes)
|
||||
.map_err(|e| ProxyError::Internal(format!("Failed to parse request body: {e}")))?;
|
||||
|
||||
let mut ctx =
|
||||
RequestContext::new(&state, &body, &headers, AppType::Codex, "Codex", "codex").await?;
|
||||
let endpoint = endpoint_with_query(&uri, "/responses/compact");
|
||||
|
||||
let is_stream = body
|
||||
.get("stream")
|
||||
@@ -384,9 +455,10 @@ pub async fn handle_responses_compact(
|
||||
let result = match forwarder
|
||||
.forward_with_retry(
|
||||
&AppType::Codex,
|
||||
"/responses/compact",
|
||||
&endpoint,
|
||||
body,
|
||||
headers,
|
||||
extensions,
|
||||
ctx.get_providers(),
|
||||
)
|
||||
.await
|
||||
@@ -415,9 +487,19 @@ pub async fn handle_responses_compact(
|
||||
pub async fn handle_gemini(
|
||||
State(state): State<ProxyState>,
|
||||
uri: axum::http::Uri,
|
||||
headers: axum::http::HeaderMap,
|
||||
Json(body): Json<Value>,
|
||||
request: axum::extract::Request,
|
||||
) -> Result<axum::response::Response, ProxyError> {
|
||||
let (parts, req_body) = request.into_parts();
|
||||
let 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: Value = serde_json::from_slice(&body_bytes)
|
||||
.map_err(|e| ProxyError::Internal(format!("Failed to parse request body: {e}")))?;
|
||||
|
||||
// Gemini 的模型名称在 URI 中
|
||||
let mut ctx = RequestContext::new(&state, &body, &headers, AppType::Gemini, "Gemini", "gemini")
|
||||
.await?
|
||||
@@ -441,6 +523,7 @@ pub async fn handle_gemini(
|
||||
endpoint,
|
||||
body,
|
||||
headers,
|
||||
extensions,
|
||||
ctx.get_providers(),
|
||||
)
|
||||
.await
|
||||
|
||||
@@ -219,7 +219,12 @@ fn build_client(proxy_url: Option<&str>) -> Result<Client, String> {
|
||||
.timeout(Duration::from_secs(600))
|
||||
.connect_timeout(Duration::from_secs(30))
|
||||
.pool_max_idle_per_host(10)
|
||||
.tcp_keepalive(Duration::from_secs(60));
|
||||
.tcp_keepalive(Duration::from_secs(60))
|
||||
// 禁用 reqwest 自动解压:防止 reqwest 覆盖客户端原始 accept-encoding header。
|
||||
// 响应解压由 response_processor 根据 content-encoding 手动处理。
|
||||
.no_gzip()
|
||||
.no_brotli()
|
||||
.no_deflate();
|
||||
|
||||
// 有代理地址则使用代理,否则跟随系统代理
|
||||
if let Some(url) = proxy_url {
|
||||
@@ -332,7 +337,7 @@ pub fn mask_url(url: &str) -> String {
|
||||
/// 根据供应商单独代理配置构建代理 URL
|
||||
///
|
||||
/// 将 ProviderProxyConfig 转换为代理 URL 字符串
|
||||
fn build_proxy_url_from_config(config: &ProviderProxyConfig) -> Option<String> {
|
||||
pub fn build_proxy_url_from_config(config: &ProviderProxyConfig) -> Option<String> {
|
||||
let proxy_type = config.proxy_type.as_deref().unwrap_or("http");
|
||||
let host = config.proxy_host.as_deref()?;
|
||||
let port = config.proxy_port?;
|
||||
@@ -387,6 +392,9 @@ pub fn build_client_for_provider(proxy_config: Option<&ProviderProxyConfig>) ->
|
||||
.connect_timeout(Duration::from_secs(30))
|
||||
.pool_max_idle_per_host(10)
|
||||
.tcp_keepalive(Duration::from_secs(60))
|
||||
.no_gzip()
|
||||
.no_brotli()
|
||||
.no_deflate()
|
||||
.proxy(proxy)
|
||||
.build()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,685 @@
|
||||
//! Hyper-based HTTP client for proxy forwarding
|
||||
//!
|
||||
//! Uses raw TCP/TLS writes to preserve exact original header name casing.
|
||||
//! Supports HTTP CONNECT tunneling through upstream proxies.
|
||||
//! Falls back to hyper-util Client (title-case headers) when raw write is not feasible.
|
||||
|
||||
use super::ProxyError;
|
||||
use bytes::Bytes;
|
||||
use futures::stream::Stream;
|
||||
use http_body_util::BodyExt;
|
||||
use hyper_rustls::HttpsConnectorBuilder;
|
||||
use hyper_util::{client::legacy::Client, rt::TokioExecutor};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
/// Our own header case map: maps lowercase header name → original wire-casing bytes.
|
||||
///
|
||||
/// This is a backup mechanism independent of hyper's internal `HeaderCaseMap` (which is
|
||||
/// `pub(crate)` and cannot be directly inspected or constructed from outside hyper).
|
||||
///
|
||||
/// Populated in `server.rs` by peeking at raw TCP bytes before hyper parses them.
|
||||
/// Used in `send_request` to manually write headers with original casing when hyper's
|
||||
/// own mechanism fails.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct OriginalHeaderCases {
|
||||
/// Ordered list of (lowercase_name, original_wire_bytes) pairs.
|
||||
/// Multiple entries with the same name are allowed (for repeated headers).
|
||||
pub cases: Vec<(String, Vec<u8>)>,
|
||||
}
|
||||
|
||||
impl OriginalHeaderCases {
|
||||
/// Parse raw HTTP request bytes (from TcpStream::peek) to extract original header casings.
|
||||
pub fn from_raw_bytes(buf: &[u8]) -> Self {
|
||||
let mut headers_buf = [httparse::EMPTY_HEADER; 128];
|
||||
let mut req = httparse::Request::new(&mut headers_buf);
|
||||
// We don't care if parsing is partial — we just want the header names we can get
|
||||
let _ = req.parse(buf);
|
||||
|
||||
let mut cases = Vec::new();
|
||||
for header in req.headers.iter() {
|
||||
if header.name.is_empty() {
|
||||
break;
|
||||
}
|
||||
cases.push((
|
||||
header.name.to_ascii_lowercase(),
|
||||
header.name.as_bytes().to_vec(),
|
||||
));
|
||||
}
|
||||
|
||||
Self { cases }
|
||||
}
|
||||
}
|
||||
|
||||
type HyperClient = Client<
|
||||
hyper_rustls::HttpsConnector<hyper_util::client::legacy::connect::HttpConnector>,
|
||||
http_body_util::Full<Bytes>,
|
||||
>;
|
||||
|
||||
/// Lazily-initialized hyper client with header-case preservation enabled.
|
||||
fn global_hyper_client() -> &'static HyperClient {
|
||||
static CLIENT: OnceLock<HyperClient> = OnceLock::new();
|
||||
CLIENT.get_or_init(|| {
|
||||
let connector = HttpsConnectorBuilder::new()
|
||||
.with_webpki_roots()
|
||||
.https_or_http()
|
||||
.enable_http1()
|
||||
.build();
|
||||
|
||||
Client::builder(TokioExecutor::new())
|
||||
.http1_preserve_header_case(true)
|
||||
.http1_title_case_headers(true)
|
||||
.build(connector)
|
||||
})
|
||||
}
|
||||
|
||||
/// Unified response wrapper that can hold either a hyper or reqwest response.
|
||||
///
|
||||
/// The hyper variant is used for the main (direct) path with header-case preservation.
|
||||
/// The reqwest variant is the fallback when an upstream HTTP/SOCKS5 proxy is configured.
|
||||
pub enum ProxyResponse {
|
||||
Hyper(hyper::Response<hyper::body::Incoming>),
|
||||
Reqwest(reqwest::Response),
|
||||
}
|
||||
|
||||
impl ProxyResponse {
|
||||
pub fn status(&self) -> http::StatusCode {
|
||||
match self {
|
||||
Self::Hyper(r) => r.status(),
|
||||
Self::Reqwest(r) => r.status(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn headers(&self) -> &http::HeaderMap {
|
||||
match self {
|
||||
Self::Hyper(r) => r.headers(),
|
||||
Self::Reqwest(r) => r.headers(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Shortcut: extract `content-type` header value as `&str`.
|
||||
pub fn content_type(&self) -> Option<&str> {
|
||||
self.headers()
|
||||
.get("content-type")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
}
|
||||
|
||||
/// Check if the response is an SSE stream.
|
||||
pub fn is_sse(&self) -> bool {
|
||||
self.content_type()
|
||||
.map(|ct| ct.contains("text/event-stream"))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Consume the response and collect the full body into `Bytes`.
|
||||
pub async fn bytes(self) -> Result<Bytes, ProxyError> {
|
||||
match self {
|
||||
Self::Hyper(r) => {
|
||||
let collected = r.into_body().collect().await.map_err(|e| {
|
||||
ProxyError::ForwardFailed(format!("Failed to read response body: {e}"))
|
||||
})?;
|
||||
Ok(collected.to_bytes())
|
||||
}
|
||||
Self::Reqwest(r) => r.bytes().await.map_err(|e| {
|
||||
ProxyError::ForwardFailed(format!("Failed to read response body: {e}"))
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Consume the response and return a byte-chunk stream (for SSE pass-through).
|
||||
pub fn bytes_stream(self) -> impl Stream<Item = Result<Bytes, std::io::Error>> + Send {
|
||||
use futures::StreamExt;
|
||||
|
||||
match self {
|
||||
Self::Hyper(r) => {
|
||||
let body = r.into_body();
|
||||
let stream = futures::stream::unfold(body, |mut body| async {
|
||||
match body.frame().await {
|
||||
Some(Ok(frame)) => {
|
||||
if let Ok(data) = frame.into_data() {
|
||||
if data.is_empty() {
|
||||
Some((Ok(Bytes::new()), body))
|
||||
} else {
|
||||
Some((Ok(data), body))
|
||||
}
|
||||
} else {
|
||||
Some((Ok(Bytes::new()), body))
|
||||
}
|
||||
}
|
||||
Some(Err(e)) => Some((Err(std::io::Error::other(e.to_string())), body)),
|
||||
None => None,
|
||||
}
|
||||
})
|
||||
.filter(|result| {
|
||||
futures::future::ready(!matches!(result, Ok(ref b) if b.is_empty()))
|
||||
});
|
||||
Box::pin(stream)
|
||||
as std::pin::Pin<Box<dyn Stream<Item = Result<Bytes, std::io::Error>> + Send>>
|
||||
}
|
||||
Self::Reqwest(r) => {
|
||||
let stream = r
|
||||
.bytes_stream()
|
||||
.map(|r| r.map_err(|e| std::io::Error::other(e.to_string())));
|
||||
Box::pin(stream)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Send an HTTP request with header-case preservation.
|
||||
///
|
||||
/// Uses a two-tier strategy:
|
||||
/// 1. Primary: raw HTTP/1.1 write via TLS stream with exact original header casing
|
||||
/// (from `OriginalHeaderCases` captured by peek in server.rs), then hand off to
|
||||
/// hyper for response parsing.
|
||||
/// 2. Fallback: hyper-util Client with `title_case_headers(true)` when raw write
|
||||
/// isn't feasible (e.g., missing original cases).
|
||||
///
|
||||
/// The caller is expected to include `Host` in the supplied `headers` at the
|
||||
/// correct position.
|
||||
///
|
||||
/// `proxy_url`: optional upstream HTTP proxy URL (e.g. `http://127.0.0.1:7890`).
|
||||
/// When set, the raw write path uses HTTP CONNECT tunneling through the proxy,
|
||||
/// so header-case preservation works even when an upstream proxy is configured.
|
||||
pub async fn send_request(
|
||||
uri: http::Uri,
|
||||
method: http::Method,
|
||||
headers: http::HeaderMap,
|
||||
original_extensions: http::Extensions,
|
||||
body: Vec<u8>,
|
||||
timeout: std::time::Duration,
|
||||
proxy_url: Option<&str>,
|
||||
) -> Result<ProxyResponse, ProxyError> {
|
||||
// Extract our own OriginalHeaderCases if available
|
||||
let original_cases = original_extensions.get::<OriginalHeaderCases>().cloned();
|
||||
let has_cases = original_cases
|
||||
.as_ref()
|
||||
.map(|c| !c.cases.is_empty())
|
||||
.unwrap_or(false);
|
||||
|
||||
log::debug!(
|
||||
"[HyperClient] Sending request: uri={uri}, header_count={}, \
|
||||
has_host={}, has_original_cases={has_cases}, proxy={:?}",
|
||||
headers.len(),
|
||||
headers.contains_key(http::header::HOST),
|
||||
proxy_url,
|
||||
);
|
||||
|
||||
if has_cases {
|
||||
// Primary path: use raw write + hyper handshake for exact header casing
|
||||
let result = tokio::time::timeout(
|
||||
timeout,
|
||||
send_raw_request(
|
||||
&uri,
|
||||
&method,
|
||||
&headers,
|
||||
original_cases.as_ref().unwrap(),
|
||||
&body,
|
||||
proxy_url,
|
||||
),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| ProxyError::Timeout(format!("请求超时: {}s", timeout.as_secs())))?;
|
||||
|
||||
match result {
|
||||
Ok(resp) => return Ok(resp),
|
||||
Err(e) => {
|
||||
if proxy_url.is_some() {
|
||||
// Don't bypass configured proxy with direct connect fallback
|
||||
return Err(e);
|
||||
}
|
||||
log::warn!("[HyperClient] Raw write failed, falling back to hyper-util: {e}");
|
||||
// Fall through to hyper-util Client
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: hyper-util Client (title-case headers, no proxy support)
|
||||
let mut req = http::Request::builder()
|
||||
.method(method)
|
||||
.uri(&uri)
|
||||
.body(http_body_util::Full::new(Bytes::from(body)))
|
||||
.map_err(|e| ProxyError::ForwardFailed(format!("Failed to build request: {e}")))?;
|
||||
|
||||
*req.headers_mut() = headers;
|
||||
*req.extensions_mut() = original_extensions;
|
||||
|
||||
let client = global_hyper_client();
|
||||
let resp = tokio::time::timeout(timeout, client.request(req))
|
||||
.await
|
||||
.map_err(|_| ProxyError::Timeout(format!("请求超时: {}s", timeout.as_secs())))?
|
||||
.map_err(|e| ProxyError::ForwardFailed(format!("上游请求失败: {e}")))?;
|
||||
|
||||
Ok(ProxyResponse::Hyper(resp))
|
||||
}
|
||||
|
||||
/// TCP or TLS stream returned by `connect_via_proxy`.
|
||||
///
|
||||
/// When the proxy URL uses `https://`, the connection to the proxy itself is
|
||||
/// TLS-wrapped before sending the CONNECT request. The enum lets
|
||||
/// `send_raw_request` work with either variant generically.
|
||||
enum ProxyStream {
|
||||
Tcp(tokio::net::TcpStream),
|
||||
Tls(Box<tokio_rustls::client::TlsStream<tokio::net::TcpStream>>),
|
||||
}
|
||||
|
||||
impl tokio::io::AsyncRead for ProxyStream {
|
||||
fn poll_read(
|
||||
self: std::pin::Pin<&mut Self>,
|
||||
cx: &mut std::task::Context<'_>,
|
||||
buf: &mut tokio::io::ReadBuf<'_>,
|
||||
) -> std::task::Poll<std::io::Result<()>> {
|
||||
match self.get_mut() {
|
||||
ProxyStream::Tcp(s) => std::pin::Pin::new(s).poll_read(cx, buf),
|
||||
ProxyStream::Tls(s) => std::pin::Pin::new(s).poll_read(cx, buf),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl tokio::io::AsyncWrite for ProxyStream {
|
||||
fn poll_write(
|
||||
self: std::pin::Pin<&mut Self>,
|
||||
cx: &mut std::task::Context<'_>,
|
||||
buf: &[u8],
|
||||
) -> std::task::Poll<std::io::Result<usize>> {
|
||||
match self.get_mut() {
|
||||
ProxyStream::Tcp(s) => std::pin::Pin::new(s).poll_write(cx, buf),
|
||||
ProxyStream::Tls(s) => std::pin::Pin::new(s).poll_write(cx, buf),
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_flush(
|
||||
self: std::pin::Pin<&mut Self>,
|
||||
cx: &mut std::task::Context<'_>,
|
||||
) -> std::task::Poll<std::io::Result<()>> {
|
||||
match self.get_mut() {
|
||||
ProxyStream::Tcp(s) => std::pin::Pin::new(s).poll_flush(cx),
|
||||
ProxyStream::Tls(s) => std::pin::Pin::new(s).poll_flush(cx),
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_shutdown(
|
||||
self: std::pin::Pin<&mut Self>,
|
||||
cx: &mut std::task::Context<'_>,
|
||||
) -> std::task::Poll<std::io::Result<()>> {
|
||||
match self.get_mut() {
|
||||
ProxyStream::Tcp(s) => std::pin::Pin::new(s).poll_shutdown(cx),
|
||||
ProxyStream::Tls(s) => std::pin::Pin::new(s).poll_shutdown(cx),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Send request via raw TCP/TLS with exact original header casing.
|
||||
///
|
||||
/// When `proxy_url` is provided, establishes an HTTP CONNECT tunnel through
|
||||
/// the proxy first, then performs TLS + raw write through the tunnel.
|
||||
/// This preserves header casing even when an upstream proxy is configured.
|
||||
async fn send_raw_request(
|
||||
uri: &http::Uri,
|
||||
method: &http::Method,
|
||||
headers: &http::HeaderMap,
|
||||
original_cases: &OriginalHeaderCases,
|
||||
body: &[u8],
|
||||
proxy_url: Option<&str>,
|
||||
) -> Result<ProxyResponse, ProxyError> {
|
||||
use tokio::io::AsyncWriteExt;
|
||||
|
||||
let scheme = uri.scheme_str().unwrap_or("https");
|
||||
let host = uri
|
||||
.host()
|
||||
.ok_or_else(|| ProxyError::ForwardFailed("URI has no host".into()))?;
|
||||
let port = uri
|
||||
.port_u16()
|
||||
.unwrap_or(if scheme == "https" { 443 } else { 80 });
|
||||
let path_and_query = uri.path_and_query().map(|pq| pq.as_str()).unwrap_or("/");
|
||||
|
||||
// Build raw HTTP request bytes
|
||||
let raw = build_raw_request(method, path_and_query, headers, original_cases, body);
|
||||
|
||||
// Establish TCP connection — either direct or through HTTP CONNECT proxy
|
||||
let stream = if let Some(proxy) = proxy_url {
|
||||
connect_via_proxy(proxy, host, port).await?
|
||||
} else {
|
||||
ProxyStream::Tcp(
|
||||
tokio::net::TcpStream::connect((host, port))
|
||||
.await
|
||||
.map_err(|e| ProxyError::ForwardFailed(format!("TCP connect failed: {e}")))?,
|
||||
)
|
||||
};
|
||||
|
||||
if scheme == "https" {
|
||||
let tls_connector = global_tls_connector();
|
||||
let server_name = rustls::pki_types::ServerName::try_from(host.to_string())
|
||||
.map_err(|e| ProxyError::ForwardFailed(format!("Invalid server name: {e}")))?;
|
||||
let mut tls_stream = tls_connector
|
||||
.connect(server_name, stream)
|
||||
.await
|
||||
.map_err(|e| ProxyError::ForwardFailed(format!("TLS handshake failed: {e}")))?;
|
||||
|
||||
tls_stream
|
||||
.write_all(&raw)
|
||||
.await
|
||||
.map_err(|e| ProxyError::ForwardFailed(format!("Write failed: {e}")))?;
|
||||
|
||||
let filtered = WriteFilter::new(tls_stream);
|
||||
do_hyper_response(filtered, method.clone()).await
|
||||
} else {
|
||||
let mut stream = stream;
|
||||
stream
|
||||
.write_all(&raw)
|
||||
.await
|
||||
.map_err(|e| ProxyError::ForwardFailed(format!("Write failed: {e}")))?;
|
||||
|
||||
let filtered = WriteFilter::new(stream);
|
||||
do_hyper_response(filtered, method.clone()).await
|
||||
}
|
||||
}
|
||||
|
||||
/// Establish a connection through an HTTP CONNECT proxy tunnel.
|
||||
///
|
||||
/// 1. Connect TCP to the proxy server (TLS-wrapped when `https://` proxy)
|
||||
/// 2. Send `CONNECT host:port HTTP/1.1` with optional `Proxy-Authorization`
|
||||
/// 3. Read the proxy's 200 response (407 → `AuthError`)
|
||||
/// 4. Return the tunneled stream (ready for target TLS handshake + raw write)
|
||||
async fn connect_via_proxy(
|
||||
proxy_url: &str,
|
||||
target_host: &str,
|
||||
target_port: u16,
|
||||
) -> Result<ProxyStream, ProxyError> {
|
||||
use base64::Engine;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
|
||||
|
||||
let parsed = url::Url::parse(proxy_url)
|
||||
.map_err(|e| ProxyError::ForwardFailed(format!("Invalid proxy URL: {e}")))?;
|
||||
|
||||
let proxy_host = parsed
|
||||
.host_str()
|
||||
.ok_or_else(|| ProxyError::ForwardFailed("Proxy URL has no host".into()))?;
|
||||
let proxy_port = parsed
|
||||
.port()
|
||||
.unwrap_or(if parsed.scheme() == "https" { 443 } else { 80 });
|
||||
|
||||
// Build Proxy-Authorization header if credentials are present
|
||||
let proxy_auth = if !parsed.username().is_empty() {
|
||||
let password = parsed.password().unwrap_or("");
|
||||
let credentials = format!("{}:{}", parsed.username(), password);
|
||||
let encoded = base64::engine::general_purpose::STANDARD.encode(credentials);
|
||||
Some(format!("Proxy-Authorization: Basic {encoded}\r\n"))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// Connect to the proxy
|
||||
let tcp = tokio::net::TcpStream::connect((proxy_host, proxy_port))
|
||||
.await
|
||||
.map_err(|e| ProxyError::ForwardFailed(format!("Proxy TCP connect failed: {e}")))?;
|
||||
|
||||
// Wrap with TLS if the proxy URL uses https://
|
||||
let mut stream: ProxyStream = if parsed.scheme() == "https" {
|
||||
let tls_connector = global_tls_connector();
|
||||
let server_name = rustls::pki_types::ServerName::try_from(proxy_host.to_string())
|
||||
.map_err(|e| ProxyError::ForwardFailed(format!("Invalid proxy server name: {e}")))?;
|
||||
let tls_stream = tls_connector
|
||||
.connect(server_name, tcp)
|
||||
.await
|
||||
.map_err(|e| ProxyError::ForwardFailed(format!("Proxy TLS handshake failed: {e}")))?;
|
||||
ProxyStream::Tls(Box::new(tls_stream))
|
||||
} else {
|
||||
ProxyStream::Tcp(tcp)
|
||||
};
|
||||
|
||||
// Send CONNECT request
|
||||
let mut connect_req = format!(
|
||||
"CONNECT {target_host}:{target_port} HTTP/1.1\r\n\
|
||||
Host: {target_host}:{target_port}\r\n"
|
||||
);
|
||||
if let Some(auth) = &proxy_auth {
|
||||
connect_req.push_str(auth);
|
||||
}
|
||||
connect_req.push_str("\r\n");
|
||||
|
||||
stream
|
||||
.write_all(connect_req.as_bytes())
|
||||
.await
|
||||
.map_err(|e| ProxyError::ForwardFailed(format!("CONNECT write failed: {e}")))?;
|
||||
|
||||
// Read the proxy's response status line
|
||||
let mut reader = BufReader::new(&mut stream);
|
||||
let mut status_line = String::new();
|
||||
reader
|
||||
.read_line(&mut status_line)
|
||||
.await
|
||||
.map_err(|e| ProxyError::ForwardFailed(format!("CONNECT read failed: {e}")))?;
|
||||
|
||||
// Expect "HTTP/1.1 200 ..." or "HTTP/1.0 200 ..."
|
||||
if !status_line.contains(" 200 ") {
|
||||
if status_line.contains(" 407 ") {
|
||||
return Err(ProxyError::AuthError(format!(
|
||||
"Proxy authentication required (407): {}",
|
||||
status_line.trim()
|
||||
)));
|
||||
}
|
||||
return Err(ProxyError::ForwardFailed(format!(
|
||||
"Proxy CONNECT rejected: {}",
|
||||
status_line.trim()
|
||||
)));
|
||||
}
|
||||
|
||||
// Drain remaining response headers (until empty line)
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
reader
|
||||
.read_line(&mut line)
|
||||
.await
|
||||
.map_err(|e| ProxyError::ForwardFailed(format!("CONNECT header read: {e}")))?;
|
||||
if line.trim().is_empty() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// BufReader might have buffered data; drop it to get raw stream back.
|
||||
// Since CONNECT response is headers-only (no body), and we read until \r\n\r\n,
|
||||
// the BufReader buffer should be empty at this point.
|
||||
drop(reader);
|
||||
|
||||
log::debug!(
|
||||
"[HyperClient] CONNECT tunnel established via {proxy_host}:{proxy_port} -> {target_host}:{target_port}"
|
||||
);
|
||||
|
||||
Ok(stream)
|
||||
}
|
||||
|
||||
/// Lazily-initialized TLS connector for raw connections.
|
||||
///
|
||||
/// Loads both webpki roots AND native system certificates so that
|
||||
/// proxy MITM CAs (e.g. Clash, mitmproxy) installed in the system
|
||||
/// keychain are trusted through the CONNECT tunnel.
|
||||
fn global_tls_connector() -> &'static tokio_rustls::TlsConnector {
|
||||
static CONNECTOR: OnceLock<tokio_rustls::TlsConnector> = OnceLock::new();
|
||||
CONNECTOR.get_or_init(|| {
|
||||
let mut root_store = rustls::RootCertStore::empty();
|
||||
// Baseline: Mozilla/webpki roots
|
||||
root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
|
||||
// Native system certs (includes user-installed proxy CAs)
|
||||
let native = rustls_native_certs::load_native_certs();
|
||||
let (added, _errors) = root_store.add_parsable_certificates(native.certs);
|
||||
log::debug!("[HyperClient] TLS root store: webpki + {added} native certs");
|
||||
let config = rustls::ClientConfig::builder()
|
||||
.with_root_certificates(root_store)
|
||||
.with_no_client_auth();
|
||||
tokio_rustls::TlsConnector::from(std::sync::Arc::new(config))
|
||||
})
|
||||
}
|
||||
|
||||
/// Build raw HTTP/1.1 request bytes with original header casing.
|
||||
fn build_raw_request(
|
||||
method: &http::Method,
|
||||
path_and_query: &str,
|
||||
headers: &http::HeaderMap,
|
||||
original_cases: &OriginalHeaderCases,
|
||||
body: &[u8],
|
||||
) -> Vec<u8> {
|
||||
let mut raw = Vec::with_capacity(4096 + body.len());
|
||||
|
||||
// Request line
|
||||
raw.extend_from_slice(method.as_str().as_bytes());
|
||||
raw.extend_from_slice(b" ");
|
||||
raw.extend_from_slice(path_and_query.as_bytes());
|
||||
raw.extend_from_slice(b" HTTP/1.1\r\n");
|
||||
|
||||
// Headers with original casing, emitted in original wire order.
|
||||
//
|
||||
// Strategy:
|
||||
// 1. Walk `original_cases.cases` in order — this preserves the exact
|
||||
// header sequence the client sent. For each entry, emit the stored
|
||||
// original-casing name plus the current value from `headers` (the
|
||||
// proxy may have rewritten the value, e.g. Authorization).
|
||||
// Repeated headers with the same name are handled by tracking a
|
||||
// per-name value cursor so we step through `get_all()` in order.
|
||||
// 2. After the original headers, append any headers that exist in
|
||||
// `headers` but were not present in the original request (i.e. added
|
||||
// by the proxy). These are emitted in lowercase.
|
||||
//
|
||||
// This replaces the old `for name in headers.keys()` loop which iterated
|
||||
// in hash-map order, destroying the original header sequence.
|
||||
let mut emitted: std::collections::HashSet<String> =
|
||||
std::collections::HashSet::with_capacity(original_cases.cases.len());
|
||||
// Per-name cursor: how many values we have already emitted for each name.
|
||||
let mut value_cursor: std::collections::HashMap<String, usize> =
|
||||
std::collections::HashMap::with_capacity(original_cases.cases.len());
|
||||
|
||||
for (lower_name, orig_name_bytes) in &original_cases.cases {
|
||||
if let Ok(header_name) = http::header::HeaderName::from_bytes(lower_name.as_bytes()) {
|
||||
let all_values: Vec<_> = headers.get_all(&header_name).iter().collect();
|
||||
let cursor = value_cursor.entry(lower_name.clone()).or_insert(0);
|
||||
if let Some(value) = all_values.get(*cursor) {
|
||||
raw.extend_from_slice(orig_name_bytes);
|
||||
raw.extend_from_slice(b": ");
|
||||
raw.extend_from_slice(value.as_bytes());
|
||||
raw.extend_from_slice(b"\r\n");
|
||||
*cursor += 1;
|
||||
emitted.insert(lower_name.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Append proxy-added headers (not present in the original request).
|
||||
for name in headers.keys() {
|
||||
let lower = name.as_str().to_ascii_lowercase();
|
||||
if !emitted.contains(&lower) {
|
||||
for value in headers.get_all(name) {
|
||||
raw.extend_from_slice(name.as_str().as_bytes());
|
||||
raw.extend_from_slice(b": ");
|
||||
raw.extend_from_slice(value.as_bytes());
|
||||
raw.extend_from_slice(b"\r\n");
|
||||
}
|
||||
emitted.insert(lower);
|
||||
}
|
||||
}
|
||||
|
||||
// Add Content-Length if not already present
|
||||
if !headers.contains_key(http::header::CONTENT_LENGTH) {
|
||||
raw.extend_from_slice(b"Content-Length: ");
|
||||
raw.extend_from_slice(body.len().to_string().as_bytes());
|
||||
raw.extend_from_slice(b"\r\n");
|
||||
}
|
||||
|
||||
// End of headers + body
|
||||
raw.extend_from_slice(b"\r\n");
|
||||
raw.extend_from_slice(body);
|
||||
|
||||
raw
|
||||
}
|
||||
|
||||
/// Use hyper's low-level client to parse the response on a stream where we've
|
||||
/// already written the request.
|
||||
///
|
||||
/// `WriteFilter` discards any writes from hyper (it would try to send its own
|
||||
/// request encoding), while passing reads through transparently.
|
||||
async fn do_hyper_response<S>(
|
||||
stream: WriteFilter<S>,
|
||||
method: http::Method,
|
||||
) -> Result<ProxyResponse, ProxyError>
|
||||
where
|
||||
S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static,
|
||||
{
|
||||
let io = hyper_util::rt::TokioIo::new(stream);
|
||||
|
||||
let (mut sender, conn) = hyper::client::conn::http1::Builder::new()
|
||||
.preserve_header_case(true)
|
||||
.handshake::<_, http_body_util::Full<Bytes>>(io)
|
||||
.await
|
||||
.map_err(|e| ProxyError::ForwardFailed(format!("Handshake failed: {e}")))?;
|
||||
|
||||
// Spawn the connection driver (reads responses from the stream)
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = conn.await {
|
||||
log::debug!("[HyperClient] raw conn driver error: {e}");
|
||||
}
|
||||
});
|
||||
|
||||
// Send a dummy request through hyper — hyper will encode this and try to write it,
|
||||
// but WriteFilter discards all writes. Hyper will then read the response from the stream.
|
||||
let dummy_req = http::Request::builder()
|
||||
.method(method)
|
||||
.uri("/")
|
||||
.body(http_body_util::Full::new(Bytes::new()))
|
||||
.map_err(|e| ProxyError::ForwardFailed(format!("Build dummy request: {e}")))?;
|
||||
|
||||
let resp = sender
|
||||
.send_request(dummy_req)
|
||||
.await
|
||||
.map_err(|e| ProxyError::ForwardFailed(format!("Response parse failed: {e}")))?;
|
||||
|
||||
Ok(ProxyResponse::Hyper(resp))
|
||||
}
|
||||
|
||||
/// A stream wrapper that discards all writes but passes reads through.
|
||||
///
|
||||
/// This lets hyper's connection driver think it sent a request (its encoded bytes
|
||||
/// go to /dev/null), while correctly parsing the response that the upstream server
|
||||
/// sends in reply to our raw-written request.
|
||||
struct WriteFilter<S> {
|
||||
inner: S,
|
||||
}
|
||||
|
||||
impl<S> WriteFilter<S> {
|
||||
fn new(inner: S) -> Self {
|
||||
Self { inner }
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: tokio::io::AsyncRead + Unpin> tokio::io::AsyncRead for WriteFilter<S> {
|
||||
fn poll_read(
|
||||
self: std::pin::Pin<&mut Self>,
|
||||
cx: &mut std::task::Context<'_>,
|
||||
buf: &mut tokio::io::ReadBuf<'_>,
|
||||
) -> std::task::Poll<std::io::Result<()>> {
|
||||
// Pass reads through to the underlying stream
|
||||
let inner = std::pin::Pin::new(&mut self.get_mut().inner);
|
||||
inner.poll_read(cx, buf)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: Unpin> tokio::io::AsyncWrite for WriteFilter<S> {
|
||||
fn poll_write(
|
||||
self: std::pin::Pin<&mut Self>,
|
||||
_cx: &mut std::task::Context<'_>,
|
||||
buf: &[u8],
|
||||
) -> std::task::Poll<std::io::Result<usize>> {
|
||||
// Discard all writes — pretend they succeeded
|
||||
std::task::Poll::Ready(Ok(buf.len()))
|
||||
}
|
||||
|
||||
fn poll_flush(
|
||||
self: std::pin::Pin<&mut Self>,
|
||||
_cx: &mut std::task::Context<'_>,
|
||||
) -> std::task::Poll<std::io::Result<()>> {
|
||||
std::task::Poll::Ready(Ok(()))
|
||||
}
|
||||
|
||||
fn poll_shutdown(
|
||||
self: std::pin::Pin<&mut Self>,
|
||||
_cx: &mut std::task::Context<'_>,
|
||||
) -> std::task::Poll<std::io::Result<()>> {
|
||||
std::task::Poll::Ready(Ok(()))
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,8 @@ pub mod srv {
|
||||
pub const STOPPED: &str = "SRV-002";
|
||||
pub const STOP_TIMEOUT: &str = "SRV-003";
|
||||
pub const TASK_ERROR: &str = "SRV-004";
|
||||
pub const ACCEPT_ERR: &str = "SRV-005";
|
||||
pub const CONN_ERR: &str = "SRV-006";
|
||||
}
|
||||
|
||||
/// 转发器日志码
|
||||
|
||||
@@ -14,6 +14,7 @@ pub mod handler_context;
|
||||
mod handlers;
|
||||
mod health;
|
||||
pub mod http_client;
|
||||
pub mod hyper_client;
|
||||
pub mod log_codes;
|
||||
pub mod model_mapper;
|
||||
pub mod provider_router;
|
||||
@@ -22,6 +23,8 @@ pub mod response_handler;
|
||||
pub mod response_processor;
|
||||
pub(crate) mod server;
|
||||
pub mod session;
|
||||
pub(crate) mod sse;
|
||||
pub(crate) mod switch_lock;
|
||||
pub mod thinking_budget_rectifier;
|
||||
pub mod thinking_optimizer;
|
||||
pub mod thinking_rectifier;
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
use super::auth::AuthInfo;
|
||||
use crate::provider::Provider;
|
||||
use crate::proxy::error::ProxyError;
|
||||
use reqwest::RequestBuilder;
|
||||
use serde_json::Value;
|
||||
|
||||
/// 供应商适配器 Trait
|
||||
@@ -14,116 +13,36 @@ use serde_json::Value;
|
||||
/// - URL 构建
|
||||
/// - 认证信息提取和头部注入
|
||||
/// - 请求/响应格式转换(可选)
|
||||
///
|
||||
/// # 示例
|
||||
///
|
||||
/// ```ignore
|
||||
/// pub struct ClaudeAdapter;
|
||||
///
|
||||
/// impl ProviderAdapter for ClaudeAdapter {
|
||||
/// fn name(&self) -> &'static str { "Claude" }
|
||||
///
|
||||
/// fn extract_base_url(&self, provider: &Provider) -> Result<String, ProxyError> {
|
||||
/// // 从 provider 配置中提取 base_url
|
||||
/// }
|
||||
///
|
||||
/// fn extract_auth(&self, provider: &Provider) -> Option<AuthInfo> {
|
||||
/// // 从 provider 配置中提取认证信息
|
||||
/// }
|
||||
///
|
||||
/// fn build_url(&self, base_url: &str, endpoint: &str) -> String {
|
||||
/// format!("{}{}", base_url.trim_end_matches('/'), endpoint)
|
||||
/// }
|
||||
///
|
||||
/// fn add_auth_headers(&self, request: RequestBuilder, auth: &AuthInfo) -> RequestBuilder {
|
||||
/// // 添加认证头
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
pub trait ProviderAdapter: Send + Sync {
|
||||
/// 适配器名称(用于日志和调试)
|
||||
fn name(&self) -> &'static str;
|
||||
|
||||
/// 从 Provider 配置中提取 base_url
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `provider` - Provider 配置
|
||||
///
|
||||
/// # Returns
|
||||
/// * `Ok(String)` - 提取到的 base_url(已去除尾部斜杠)
|
||||
/// * `Err(ProxyError)` - 提取失败
|
||||
fn extract_base_url(&self, provider: &Provider) -> Result<String, ProxyError>;
|
||||
|
||||
/// 从 Provider 配置中提取认证信息
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `provider` - Provider 配置
|
||||
///
|
||||
/// # Returns
|
||||
/// * `Some(AuthInfo)` - 提取到的认证信息
|
||||
/// * `None` - 未找到认证信息
|
||||
fn extract_auth(&self, provider: &Provider) -> Option<AuthInfo>;
|
||||
|
||||
/// 构建请求 URL
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `base_url` - 基础 URL
|
||||
/// * `endpoint` - 请求端点(如 `/v1/messages`)
|
||||
///
|
||||
/// # Returns
|
||||
/// 完整的请求 URL
|
||||
fn build_url(&self, base_url: &str, endpoint: &str) -> String;
|
||||
|
||||
/// 添加认证头到请求
|
||||
/// Return auth headers as `(name, value)` pairs.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `request` - reqwest RequestBuilder
|
||||
/// * `auth` - 认证信息
|
||||
///
|
||||
/// # Returns
|
||||
/// 添加了认证头的 RequestBuilder
|
||||
fn add_auth_headers(&self, request: RequestBuilder, auth: &AuthInfo) -> RequestBuilder;
|
||||
/// The forwarder inserts these at the position of the original auth header
|
||||
/// so that header order is preserved.
|
||||
fn get_auth_headers(&self, auth: &AuthInfo) -> Vec<(http::HeaderName, http::HeaderValue)>;
|
||||
|
||||
/// 是否需要格式转换
|
||||
///
|
||||
/// 默认返回 `false`(透传模式)。
|
||||
/// 仅当供应商需要格式转换时(如 Claude + OpenRouter 旧 OpenAI 兼容接口)才返回 `true`。
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `provider` - Provider 配置
|
||||
fn needs_transform(&self, _provider: &Provider) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// 转换请求体
|
||||
///
|
||||
/// 将请求体从一种格式转换为另一种格式(如 Anthropic → OpenAI)。
|
||||
/// 默认实现直接返回原始请求体(透传)。
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `body` - 原始请求体
|
||||
/// * `provider` - Provider 配置(用于获取模型映射等)
|
||||
///
|
||||
/// # Returns
|
||||
/// * `Ok(Value)` - 转换后的请求体
|
||||
/// * `Err(ProxyError)` - 转换失败
|
||||
fn transform_request(&self, body: Value, _provider: &Provider) -> Result<Value, ProxyError> {
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
/// 转换响应体
|
||||
///
|
||||
/// 将响应体从一种格式转换为另一种格式(如 OpenAI → Anthropic)。
|
||||
/// 默认实现直接返回原始响应体(透传)。
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `body` - 原始响应体
|
||||
///
|
||||
/// # Returns
|
||||
/// * `Ok(Value)` - 转换后的响应体
|
||||
/// * `Err(ProxyError)` - 转换失败
|
||||
///
|
||||
/// Note: 响应转换将在 handler 层集成,目前预留接口
|
||||
#[allow(dead_code)]
|
||||
fn transform_response(&self, body: Value) -> Result<Value, ProxyError> {
|
||||
Ok(body)
|
||||
|
||||
@@ -112,6 +112,13 @@ pub enum AuthStrategy {
|
||||
///
|
||||
/// 用于 Gemini CLI 等需要 OAuth 的场景
|
||||
GoogleOAuth,
|
||||
|
||||
/// GitHub Copilot 认证方式
|
||||
///
|
||||
/// - Header: `Authorization: Bearer <copilot_token>`
|
||||
///
|
||||
/// 使用动态获取的 Copilot Token(通过 GitHub OAuth 设备码流程获取)
|
||||
GitHubCopilot,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -226,6 +233,7 @@ mod tests {
|
||||
AuthStrategy::Bearer,
|
||||
AuthStrategy::Google,
|
||||
AuthStrategy::GoogleOAuth,
|
||||
AuthStrategy::GitHubCopilot,
|
||||
];
|
||||
|
||||
for (i, s1) in strategies.iter().enumerate() {
|
||||
|
||||
@@ -11,11 +11,11 @@
|
||||
//! - **Claude**: Anthropic 官方 API (x-api-key + anthropic-version)
|
||||
//! - **ClaudeAuth**: 中转服务 (仅 Bearer 认证,无 x-api-key)
|
||||
//! - **OpenRouter**: 已支持 Claude Code 兼容接口,默认透传
|
||||
//! - **GitHubCopilot**: GitHub Copilot (OAuth + Copilot Token)
|
||||
|
||||
use super::{AuthInfo, AuthStrategy, ProviderAdapter, ProviderType};
|
||||
use crate::provider::Provider;
|
||||
use crate::proxy::error::ProxyError;
|
||||
use reqwest::RequestBuilder;
|
||||
|
||||
/// 获取 Claude 供应商的 API 格式
|
||||
///
|
||||
@@ -65,6 +65,30 @@ pub fn get_claude_api_format(provider: &Provider) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn claude_api_format_needs_transform(api_format: &str) -> bool {
|
||||
matches!(api_format, "openai_chat" | "openai_responses")
|
||||
}
|
||||
|
||||
pub fn transform_claude_request_for_api_format(
|
||||
body: serde_json::Value,
|
||||
provider: &Provider,
|
||||
api_format: &str,
|
||||
) -> Result<serde_json::Value, ProxyError> {
|
||||
let cache_key = provider
|
||||
.meta
|
||||
.as_ref()
|
||||
.and_then(|m| m.prompt_cache_key.as_deref())
|
||||
.unwrap_or(&provider.id);
|
||||
|
||||
match api_format {
|
||||
"openai_responses" => {
|
||||
super::transform_responses::anthropic_to_responses(body, Some(cache_key))
|
||||
}
|
||||
"openai_chat" => super::transform::anthropic_to_openai(body, Some(cache_key)),
|
||||
_ => Ok(body),
|
||||
}
|
||||
}
|
||||
|
||||
/// Claude 适配器
|
||||
pub struct ClaudeAdapter;
|
||||
|
||||
@@ -76,10 +100,16 @@ impl ClaudeAdapter {
|
||||
/// 获取供应商类型
|
||||
///
|
||||
/// 根据 base_url 和 auth_mode 检测具体的供应商类型:
|
||||
/// - GitHubCopilot: meta.provider_type 为 github_copilot 或 base_url 包含 githubcopilot.com
|
||||
/// - OpenRouter: base_url 包含 openrouter.ai
|
||||
/// - ClaudeAuth: auth_mode 为 bearer_only
|
||||
/// - Claude: 默认 Anthropic 官方
|
||||
pub fn provider_type(&self, provider: &Provider) -> ProviderType {
|
||||
// 检测 GitHub Copilot
|
||||
if self.is_github_copilot(provider) {
|
||||
return ProviderType::GitHubCopilot;
|
||||
}
|
||||
|
||||
// 检测 OpenRouter
|
||||
if self.is_openrouter(provider) {
|
||||
return ProviderType::OpenRouter;
|
||||
@@ -93,6 +123,25 @@ impl ClaudeAdapter {
|
||||
ProviderType::Claude
|
||||
}
|
||||
|
||||
/// 检测是否为 GitHub Copilot 供应商
|
||||
fn is_github_copilot(&self, provider: &Provider) -> bool {
|
||||
// 方式1: 检查 meta.provider_type
|
||||
if let Some(meta) = provider.meta.as_ref() {
|
||||
if meta.provider_type.as_deref() == Some("github_copilot") {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// 方式2: 检查 base_url(兼容旧数据的 fallback,后续应优先依赖 providerType)
|
||||
if let Ok(base_url) = self.extract_base_url(provider) {
|
||||
if base_url.contains("githubcopilot.com") {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
/// 检测是否使用 OpenRouter
|
||||
fn is_openrouter(&self, provider: &Provider) -> bool {
|
||||
if let Ok(base_url) = self.extract_base_url(provider) {
|
||||
@@ -244,6 +293,17 @@ impl ProviderAdapter for ClaudeAdapter {
|
||||
|
||||
fn extract_auth(&self, provider: &Provider) -> Option<AuthInfo> {
|
||||
let provider_type = self.provider_type(provider);
|
||||
|
||||
// GitHub Copilot 使用特殊的认证策略
|
||||
// 实际的 token 会在代理请求时动态获取
|
||||
if provider_type == ProviderType::GitHubCopilot {
|
||||
// 返回一个占位符,实际 token 由 CopilotAuthManager 动态提供
|
||||
return Some(AuthInfo::new(
|
||||
"copilot_placeholder".to_string(),
|
||||
AuthStrategy::GitHubCopilot,
|
||||
));
|
||||
}
|
||||
|
||||
let strategy = match provider_type {
|
||||
ProviderType::OpenRouter => AuthStrategy::Bearer,
|
||||
ProviderType::ClaudeAuth => AuthStrategy::ClaudeAuth,
|
||||
@@ -261,7 +321,7 @@ impl ProviderAdapter for ClaudeAdapter {
|
||||
//
|
||||
// 现在 OpenRouter 已推出 Claude Code 兼容接口,因此默认直接透传 endpoint。
|
||||
// 如需回退旧逻辑,可在 forwarder 中根据 needs_transform 改写 endpoint。
|
||||
|
||||
//
|
||||
let mut base = format!(
|
||||
"{}/{}",
|
||||
base_url.trim_end_matches('/'),
|
||||
@@ -273,42 +333,62 @@ impl ProviderAdapter for ClaudeAdapter {
|
||||
base = base.replace("/v1/v1", "/v1");
|
||||
}
|
||||
|
||||
// 为 Claude 原生 /v1/messages 端点添加 ?beta=true 参数
|
||||
// 这是某些上游服务(如 DuckCoding)验证请求来源的关键参数
|
||||
// 注意:不要为 OpenAI Chat Completions (/v1/chat/completions) 添加此参数
|
||||
// 当 apiFormat="openai_chat" 时,请求会转发到 /v1/chat/completions,
|
||||
// 但该端点是 OpenAI 标准,不支持 ?beta=true 参数
|
||||
if endpoint.contains("/v1/messages")
|
||||
&& !endpoint.contains("/v1/chat/completions")
|
||||
&& !endpoint.contains('?')
|
||||
{
|
||||
format!("{base}?beta=true")
|
||||
} else {
|
||||
base
|
||||
}
|
||||
base
|
||||
}
|
||||
|
||||
fn add_auth_headers(&self, request: RequestBuilder, auth: &AuthInfo) -> RequestBuilder {
|
||||
fn get_auth_headers(&self, auth: &AuthInfo) -> Vec<(http::HeaderName, http::HeaderValue)> {
|
||||
use http::{HeaderName, HeaderValue};
|
||||
// 注意:anthropic-version 由 forwarder.rs 统一处理(透传客户端值或设置默认值)
|
||||
// 这里不再设置 anthropic-version,避免 header 重复
|
||||
let bearer = format!("Bearer {}", auth.api_key);
|
||||
match auth.strategy {
|
||||
// Anthropic 官方: Authorization Bearer + x-api-key
|
||||
AuthStrategy::Anthropic => request
|
||||
.header("Authorization", format!("Bearer {}", auth.api_key))
|
||||
.header("x-api-key", &auth.api_key),
|
||||
// ClaudeAuth 中转服务: 仅 Bearer,无 x-api-key
|
||||
AuthStrategy::ClaudeAuth => {
|
||||
request.header("Authorization", format!("Bearer {}", auth.api_key))
|
||||
AuthStrategy::Anthropic | AuthStrategy::ClaudeAuth | AuthStrategy::Bearer => {
|
||||
vec![(
|
||||
HeaderName::from_static("authorization"),
|
||||
HeaderValue::from_str(&bearer).unwrap(),
|
||||
)]
|
||||
}
|
||||
// OpenRouter: Bearer
|
||||
AuthStrategy::Bearer => {
|
||||
request.header("Authorization", format!("Bearer {}", auth.api_key))
|
||||
AuthStrategy::GitHubCopilot => {
|
||||
vec![
|
||||
(
|
||||
HeaderName::from_static("authorization"),
|
||||
HeaderValue::from_str(&bearer).unwrap(),
|
||||
),
|
||||
(
|
||||
HeaderName::from_static("editor-version"),
|
||||
HeaderValue::from_static(super::copilot_auth::COPILOT_EDITOR_VERSION),
|
||||
),
|
||||
(
|
||||
HeaderName::from_static("editor-plugin-version"),
|
||||
HeaderValue::from_static(super::copilot_auth::COPILOT_PLUGIN_VERSION),
|
||||
),
|
||||
(
|
||||
HeaderName::from_static("copilot-integration-id"),
|
||||
HeaderValue::from_static(super::copilot_auth::COPILOT_INTEGRATION_ID),
|
||||
),
|
||||
(
|
||||
HeaderName::from_static("user-agent"),
|
||||
HeaderValue::from_static(super::copilot_auth::COPILOT_USER_AGENT),
|
||||
),
|
||||
(
|
||||
HeaderName::from_static("x-github-api-version"),
|
||||
HeaderValue::from_static(super::copilot_auth::COPILOT_API_VERSION),
|
||||
),
|
||||
(
|
||||
HeaderName::from_static("openai-intent"),
|
||||
HeaderValue::from_static("conversation-panel"),
|
||||
),
|
||||
]
|
||||
}
|
||||
_ => request,
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
fn needs_transform(&self, provider: &Provider) -> bool {
|
||||
// GitHub Copilot 总是需要格式转换 (Anthropic → OpenAI)
|
||||
if self.is_github_copilot(provider) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 根据 api_format 配置决定是否需要格式转换
|
||||
// - "anthropic" (默认): 直接透传,无需转换
|
||||
// - "openai_chat": 需要 Anthropic ↔ OpenAI Chat Completions 格式转换
|
||||
@@ -324,19 +404,7 @@ impl ProviderAdapter for ClaudeAdapter {
|
||||
body: serde_json::Value,
|
||||
provider: &Provider,
|
||||
) -> Result<serde_json::Value, ProxyError> {
|
||||
// Use meta.prompt_cache_key if set by user, otherwise fall back to provider.id
|
||||
let cache_key = provider
|
||||
.meta
|
||||
.as_ref()
|
||||
.and_then(|m| m.prompt_cache_key.as_deref())
|
||||
.unwrap_or(&provider.id);
|
||||
|
||||
match self.get_api_format(provider) {
|
||||
"openai_responses" => {
|
||||
super::transform_responses::anthropic_to_responses(body, Some(cache_key))
|
||||
}
|
||||
_ => super::transform::anthropic_to_openai(body, Some(cache_key)),
|
||||
}
|
||||
transform_claude_request_for_api_format(body, provider, self.get_api_format(provider))
|
||||
}
|
||||
|
||||
fn transform_response(&self, body: serde_json::Value) -> Result<serde_json::Value, ProxyError> {
|
||||
@@ -522,23 +590,20 @@ mod tests {
|
||||
#[test]
|
||||
fn test_build_url_anthropic() {
|
||||
let adapter = ClaudeAdapter::new();
|
||||
// /v1/messages 端点会自动添加 ?beta=true 参数
|
||||
let url = adapter.build_url("https://api.anthropic.com", "/v1/messages");
|
||||
assert_eq!(url, "https://api.anthropic.com/v1/messages?beta=true");
|
||||
assert_eq!(url, "https://api.anthropic.com/v1/messages");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_url_openrouter() {
|
||||
let adapter = ClaudeAdapter::new();
|
||||
// /v1/messages 端点会自动添加 ?beta=true 参数
|
||||
let url = adapter.build_url("https://openrouter.ai/api", "/v1/messages");
|
||||
assert_eq!(url, "https://openrouter.ai/api/v1/messages?beta=true");
|
||||
assert_eq!(url, "https://openrouter.ai/api/v1/messages");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_url_no_beta_for_other_endpoints() {
|
||||
let adapter = ClaudeAdapter::new();
|
||||
// 非 /v1/messages 端点不添加 ?beta=true
|
||||
let url = adapter.build_url("https://api.anthropic.com", "/v1/complete");
|
||||
assert_eq!(url, "https://api.anthropic.com/v1/complete");
|
||||
}
|
||||
@@ -546,16 +611,20 @@ mod tests {
|
||||
#[test]
|
||||
fn test_build_url_preserve_existing_query() {
|
||||
let adapter = ClaudeAdapter::new();
|
||||
// 已有查询参数时不重复添加
|
||||
let url = adapter.build_url("https://api.anthropic.com", "/v1/messages?foo=bar");
|
||||
assert_eq!(url, "https://api.anthropic.com/v1/messages?foo=bar");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_url_no_beta_for_github_copilot() {
|
||||
let adapter = ClaudeAdapter::new();
|
||||
let url = adapter.build_url("https://api.githubcopilot.com", "/v1/messages");
|
||||
assert_eq!(url, "https://api.githubcopilot.com/v1/messages");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_url_no_beta_for_openai_chat_completions() {
|
||||
let adapter = ClaudeAdapter::new();
|
||||
// OpenAI Chat Completions 端点不添加 ?beta=true
|
||||
// 这是 Nvidia 等 apiFormat="openai_chat" 供应商使用的端点
|
||||
let url = adapter.build_url("https://integrate.api.nvidia.com", "/v1/chat/completions");
|
||||
assert_eq!(url, "https://integrate.api.nvidia.com/v1/chat/completions");
|
||||
}
|
||||
@@ -678,4 +747,88 @@ mod tests {
|
||||
);
|
||||
assert!(!adapter.needs_transform(&unknown_format));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_github_copilot_detection_by_url() {
|
||||
let adapter = ClaudeAdapter::new();
|
||||
|
||||
// GitHub Copilot by base_url
|
||||
let copilot = create_provider(json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://api.githubcopilot.com"
|
||||
}
|
||||
}));
|
||||
assert_eq!(adapter.provider_type(&copilot), ProviderType::GitHubCopilot);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_github_copilot_detection_by_meta() {
|
||||
let adapter = ClaudeAdapter::new();
|
||||
|
||||
// GitHub Copilot by meta.provider_type
|
||||
let copilot_meta = create_provider_with_meta(
|
||||
json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://api.example.com"
|
||||
}
|
||||
}),
|
||||
ProviderMeta {
|
||||
provider_type: Some("github_copilot".to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
assert_eq!(
|
||||
adapter.provider_type(&copilot_meta),
|
||||
ProviderType::GitHubCopilot
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_github_copilot_auth() {
|
||||
let adapter = ClaudeAdapter::new();
|
||||
|
||||
let copilot = create_provider(json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://api.githubcopilot.com"
|
||||
}
|
||||
}));
|
||||
|
||||
let auth = adapter.extract_auth(&copilot).unwrap();
|
||||
assert_eq!(auth.strategy, AuthStrategy::GitHubCopilot);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_github_copilot_needs_transform() {
|
||||
let adapter = ClaudeAdapter::new();
|
||||
|
||||
let copilot = create_provider(json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://api.githubcopilot.com"
|
||||
}
|
||||
}));
|
||||
|
||||
// GitHub Copilot always needs transform
|
||||
assert!(adapter.needs_transform(&copilot));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_transform_claude_request_for_api_format_responses() {
|
||||
let provider = create_provider(json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://api.githubcopilot.com"
|
||||
}
|
||||
}));
|
||||
let body = json!({
|
||||
"model": "gpt-5.4",
|
||||
"messages": [{ "role": "user", "content": "hello" }],
|
||||
"max_tokens": 128
|
||||
});
|
||||
|
||||
let transformed =
|
||||
transform_claude_request_for_api_format(body, &provider, "openai_responses").unwrap();
|
||||
|
||||
assert_eq!(transformed["model"], "gpt-5.4");
|
||||
assert!(transformed.get("input").is_some());
|
||||
assert!(transformed.get("max_output_tokens").is_some());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ use super::{AuthInfo, AuthStrategy, ProviderAdapter};
|
||||
use crate::provider::Provider;
|
||||
use crate::proxy::error::ProxyError;
|
||||
use regex::Regex;
|
||||
use reqwest::RequestBuilder;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
/// 官方 Codex 客户端 User-Agent 正则
|
||||
@@ -174,8 +173,12 @@ impl ProviderAdapter for CodexAdapter {
|
||||
url
|
||||
}
|
||||
|
||||
fn add_auth_headers(&self, request: RequestBuilder, auth: &AuthInfo) -> RequestBuilder {
|
||||
request.header("Authorization", format!("Bearer {}", auth.api_key))
|
||||
fn get_auth_headers(&self, auth: &AuthInfo) -> Vec<(http::HeaderName, http::HeaderValue)> {
|
||||
let bearer = format!("Bearer {}", auth.api_key);
|
||||
vec![(
|
||||
http::HeaderName::from_static("authorization"),
|
||||
http::HeaderValue::from_str(&bearer).unwrap(),
|
||||
)]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -9,7 +9,6 @@
|
||||
use super::{AuthInfo, AuthStrategy, ProviderAdapter, ProviderType};
|
||||
use crate::provider::Provider;
|
||||
use crate::proxy::error::ProxyError;
|
||||
use reqwest::RequestBuilder;
|
||||
|
||||
/// Gemini 适配器
|
||||
pub struct GeminiAdapter;
|
||||
@@ -217,17 +216,26 @@ impl ProviderAdapter for GeminiAdapter {
|
||||
url
|
||||
}
|
||||
|
||||
fn add_auth_headers(&self, request: RequestBuilder, auth: &AuthInfo) -> RequestBuilder {
|
||||
fn get_auth_headers(&self, auth: &AuthInfo) -> Vec<(http::HeaderName, http::HeaderValue)> {
|
||||
use http::{HeaderName, HeaderValue};
|
||||
match auth.strategy {
|
||||
// OAuth Bearer 认证
|
||||
AuthStrategy::GoogleOAuth => {
|
||||
let token = auth.access_token.as_ref().unwrap_or(&auth.api_key);
|
||||
request
|
||||
.header("Authorization", format!("Bearer {token}"))
|
||||
.header("x-goog-api-client", "GeminiCLI/1.0")
|
||||
vec![
|
||||
(
|
||||
HeaderName::from_static("authorization"),
|
||||
HeaderValue::from_str(&format!("Bearer {token}")).unwrap(),
|
||||
),
|
||||
(
|
||||
HeaderName::from_static("x-goog-api-client"),
|
||||
HeaderValue::from_static("GeminiCLI/1.0"),
|
||||
),
|
||||
]
|
||||
}
|
||||
// API Key 认证
|
||||
_ => request.header("x-goog-api-key", &auth.api_key),
|
||||
_ => vec![(
|
||||
HeaderName::from_static("x-goog-api-key"),
|
||||
HeaderValue::from_str(&auth.api_key).unwrap(),
|
||||
)],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ mod adapter;
|
||||
mod auth;
|
||||
mod claude;
|
||||
mod codex;
|
||||
pub mod copilot_auth;
|
||||
mod gemini;
|
||||
pub mod models;
|
||||
pub mod streaming;
|
||||
@@ -29,7 +30,10 @@ use serde::{Deserialize, Serialize};
|
||||
// 公开导出
|
||||
pub use adapter::ProviderAdapter;
|
||||
pub use auth::{AuthInfo, AuthStrategy};
|
||||
pub use claude::{get_claude_api_format, ClaudeAdapter};
|
||||
pub use claude::{
|
||||
claude_api_format_needs_transform, get_claude_api_format,
|
||||
transform_claude_request_for_api_format, ClaudeAdapter,
|
||||
};
|
||||
pub use codex::CodexAdapter;
|
||||
pub use gemini::GeminiAdapter;
|
||||
|
||||
@@ -52,6 +56,8 @@ pub enum ProviderType {
|
||||
GeminiCli,
|
||||
/// OpenRouter(已支持 Claude Code 兼容接口,默认透传;保留旧转换逻辑备用)
|
||||
OpenRouter,
|
||||
/// GitHub Copilot (OAuth + Copilot Token,需要 Anthropic ↔ OpenAI 转换)
|
||||
GitHubCopilot,
|
||||
}
|
||||
|
||||
impl ProviderType {
|
||||
@@ -59,9 +65,11 @@ impl ProviderType {
|
||||
///
|
||||
/// 过去 OpenRouter 需要将 Anthropic 格式转换为 OpenAI 格式;
|
||||
/// 现在默认关闭转换(因为 OpenRouter 已支持 Claude Code 兼容接口)。
|
||||
/// GitHub Copilot 需要转换(Anthropic → OpenAI 格式)。
|
||||
#[allow(dead_code)]
|
||||
pub fn needs_transform(&self) -> bool {
|
||||
match self {
|
||||
ProviderType::GitHubCopilot => true,
|
||||
ProviderType::OpenRouter => false,
|
||||
_ => false,
|
||||
}
|
||||
@@ -77,6 +85,7 @@ impl ProviderType {
|
||||
"https://generativelanguage.googleapis.com"
|
||||
}
|
||||
ProviderType::OpenRouter => "https://openrouter.ai/api",
|
||||
ProviderType::GitHubCopilot => "https://api.githubcopilot.com",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,9 +96,20 @@ impl ProviderType {
|
||||
pub fn from_app_type_and_config(app_type: &AppType, provider: &Provider) -> Self {
|
||||
match app_type {
|
||||
AppType::Claude => {
|
||||
// 检测是否为 OpenRouter
|
||||
// 检测是否为 GitHub Copilot
|
||||
if let Some(meta) = provider.meta.as_ref() {
|
||||
if meta.provider_type.as_deref() == Some("github_copilot") {
|
||||
return ProviderType::GitHubCopilot;
|
||||
}
|
||||
}
|
||||
|
||||
// 检测 base_url 是否为 GitHub Copilot
|
||||
let adapter = ClaudeAdapter::new();
|
||||
if let Ok(base_url) = adapter.extract_base_url(provider) {
|
||||
if base_url.contains("githubcopilot.com") {
|
||||
return ProviderType::GitHubCopilot;
|
||||
}
|
||||
// 检测是否为 OpenRouter
|
||||
if base_url.contains("openrouter.ai") {
|
||||
return ProviderType::OpenRouter;
|
||||
}
|
||||
@@ -154,6 +174,7 @@ impl ProviderType {
|
||||
ProviderType::Gemini => "gemini",
|
||||
ProviderType::GeminiCli => "gemini_cli",
|
||||
ProviderType::OpenRouter => "openrouter",
|
||||
ProviderType::GitHubCopilot => "github_copilot",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -175,6 +196,9 @@ impl std::str::FromStr for ProviderType {
|
||||
"gemini" => Ok(ProviderType::Gemini),
|
||||
"gemini_cli" | "gemini-cli" => Ok(ProviderType::GeminiCli),
|
||||
"openrouter" => Ok(ProviderType::OpenRouter),
|
||||
"github_copilot" | "github-copilot" | "githubcopilot" => {
|
||||
Ok(ProviderType::GitHubCopilot)
|
||||
}
|
||||
_ => Err(format!("Invalid provider type: {s}")),
|
||||
}
|
||||
}
|
||||
@@ -201,9 +225,10 @@ pub fn get_adapter(app_type: &AppType) -> Box<dyn ProviderAdapter> {
|
||||
#[allow(dead_code)]
|
||||
pub fn get_adapter_for_provider_type(provider_type: &ProviderType) -> Box<dyn ProviderAdapter> {
|
||||
match provider_type {
|
||||
ProviderType::Claude | ProviderType::ClaudeAuth | ProviderType::OpenRouter => {
|
||||
Box::new(ClaudeAdapter::new())
|
||||
}
|
||||
ProviderType::Claude
|
||||
| ProviderType::ClaudeAuth
|
||||
| ProviderType::OpenRouter
|
||||
| ProviderType::GitHubCopilot => Box::new(ClaudeAdapter::new()),
|
||||
ProviderType::Codex => Box::new(CodexAdapter::new()),
|
||||
ProviderType::Gemini | ProviderType::GeminiCli => Box::new(GeminiAdapter::new()),
|
||||
}
|
||||
@@ -239,6 +264,7 @@ mod tests {
|
||||
assert!(!ProviderType::Gemini.needs_transform());
|
||||
assert!(!ProviderType::GeminiCli.needs_transform());
|
||||
assert!(!ProviderType::OpenRouter.needs_transform());
|
||||
assert!(ProviderType::GitHubCopilot.needs_transform());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -267,6 +293,10 @@ mod tests {
|
||||
ProviderType::OpenRouter.default_endpoint(),
|
||||
"https://openrouter.ai/api"
|
||||
);
|
||||
assert_eq!(
|
||||
ProviderType::GitHubCopilot.default_endpoint(),
|
||||
"https://api.githubcopilot.com"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -303,6 +333,18 @@ mod tests {
|
||||
"openrouter".parse::<ProviderType>().unwrap(),
|
||||
ProviderType::OpenRouter
|
||||
);
|
||||
assert_eq!(
|
||||
"github_copilot".parse::<ProviderType>().unwrap(),
|
||||
ProviderType::GitHubCopilot
|
||||
);
|
||||
assert_eq!(
|
||||
"github-copilot".parse::<ProviderType>().unwrap(),
|
||||
ProviderType::GitHubCopilot
|
||||
);
|
||||
assert_eq!(
|
||||
"githubcopilot".parse::<ProviderType>().unwrap(),
|
||||
ProviderType::GitHubCopilot
|
||||
);
|
||||
assert!("invalid".parse::<ProviderType>().is_err());
|
||||
}
|
||||
|
||||
@@ -314,6 +356,7 @@ mod tests {
|
||||
assert_eq!(ProviderType::Gemini.as_str(), "gemini");
|
||||
assert_eq!(ProviderType::GeminiCli.as_str(), "gemini_cli");
|
||||
assert_eq!(ProviderType::OpenRouter.as_str(), "openrouter");
|
||||
assert_eq!(ProviderType::GitHubCopilot.as_str(), "github_copilot");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -434,6 +477,9 @@ mod tests {
|
||||
let adapter = get_adapter_for_provider_type(&ProviderType::OpenRouter);
|
||||
assert_eq!(adapter.name(), "Claude");
|
||||
|
||||
let adapter = get_adapter_for_provider_type(&ProviderType::GitHubCopilot);
|
||||
assert_eq!(adapter.name(), "Claude");
|
||||
|
||||
let adapter = get_adapter_for_provider_type(&ProviderType::Codex);
|
||||
assert_eq!(adapter.name(), "Codex");
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//!
|
||||
//! 实现 OpenAI SSE → Anthropic SSE 格式转换
|
||||
|
||||
use crate::proxy::sse::strip_sse_field;
|
||||
use bytes::Bytes;
|
||||
use futures::stream::{Stream, StreamExt};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -87,8 +88,8 @@ struct ToolBlockState {
|
||||
}
|
||||
|
||||
/// 创建 Anthropic SSE 流
|
||||
pub fn create_anthropic_sse_stream(
|
||||
stream: impl Stream<Item = Result<Bytes, reqwest::Error>> + Send + 'static,
|
||||
pub fn create_anthropic_sse_stream<E: std::error::Error + Send + 'static>(
|
||||
stream: impl Stream<Item = Result<Bytes, E>> + Send + 'static,
|
||||
) -> impl Stream<Item = Result<Bytes, std::io::Error>> + Send {
|
||||
async_stream::stream! {
|
||||
let mut buffer = String::new();
|
||||
@@ -118,7 +119,7 @@ pub fn create_anthropic_sse_stream(
|
||||
}
|
||||
|
||||
for l in line.lines() {
|
||||
if let Some(data) = l.strip_prefix("data: ") {
|
||||
if let Some(data) = strip_sse_field(l, "data") {
|
||||
if data.trim() == "[DONE]" {
|
||||
log::debug!("[Claude/OpenRouter] <<< OpenAI SSE: [DONE]");
|
||||
let event = json!({"type": "message_stop"});
|
||||
@@ -597,7 +598,9 @@ mod tests {
|
||||
"data: [DONE]\n\n"
|
||||
);
|
||||
|
||||
let upstream = stream::iter(vec![Ok(Bytes::from(input.as_bytes().to_vec()))]);
|
||||
let upstream = stream::iter(vec![Ok::<_, std::io::Error>(Bytes::from(
|
||||
input.as_bytes().to_vec(),
|
||||
))]);
|
||||
let converted = create_anthropic_sse_stream(upstream);
|
||||
let chunks: Vec<_> = converted.collect().await;
|
||||
|
||||
@@ -609,7 +612,9 @@ mod tests {
|
||||
let events: Vec<Value> = merged
|
||||
.split("\n\n")
|
||||
.filter_map(|block| {
|
||||
let data = block.lines().find_map(|line| line.strip_prefix("data: "))?;
|
||||
let data = block
|
||||
.lines()
|
||||
.find_map(|line| strip_sse_field(line, "data"))?;
|
||||
serde_json::from_str::<Value>(data).ok()
|
||||
})
|
||||
.collect();
|
||||
@@ -683,7 +688,9 @@ mod tests {
|
||||
"data: [DONE]\n\n"
|
||||
);
|
||||
|
||||
let upstream = stream::iter(vec![Ok(Bytes::from(input.as_bytes().to_vec()))]);
|
||||
let upstream = stream::iter(vec![Ok::<_, std::io::Error>(Bytes::from(
|
||||
input.as_bytes().to_vec(),
|
||||
))]);
|
||||
let converted = create_anthropic_sse_stream(upstream);
|
||||
let chunks: Vec<_> = converted.collect().await;
|
||||
let merged = chunks
|
||||
@@ -694,7 +701,9 @@ mod tests {
|
||||
let events: Vec<Value> = merged
|
||||
.split("\n\n")
|
||||
.filter_map(|block| {
|
||||
let data = block.lines().find_map(|line| line.strip_prefix("data: "))?;
|
||||
let data = block
|
||||
.lines()
|
||||
.find_map(|line| strip_sse_field(line, "data"))?;
|
||||
serde_json::from_str::<Value>(data).ok()
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
//! 与 Chat Completions 的 delta chunk 模型完全不同,需要独立的状态机处理。
|
||||
|
||||
use super::transform_responses::{build_anthropic_usage_from_responses, map_responses_stop_reason};
|
||||
use crate::proxy::sse::strip_sse_field;
|
||||
use bytes::Bytes;
|
||||
use futures::stream::{Stream, StreamExt};
|
||||
use serde_json::{json, Value};
|
||||
@@ -95,8 +96,8 @@ fn resolve_content_index(
|
||||
///
|
||||
/// 状态机跟踪: message_id, current_model, has_sent_message_start, item/content index map
|
||||
/// SSE 解析支持 named events (event: + data: 行)
|
||||
pub fn create_anthropic_sse_stream_from_responses(
|
||||
stream: impl Stream<Item = Result<Bytes, reqwest::Error>> + Send + 'static,
|
||||
pub fn create_anthropic_sse_stream_from_responses<E: std::error::Error + Send + 'static>(
|
||||
stream: impl Stream<Item = Result<Bytes, E>> + Send + 'static,
|
||||
) -> impl Stream<Item = Result<Bytes, std::io::Error>> + Send {
|
||||
async_stream::stream! {
|
||||
let mut buffer = String::new();
|
||||
@@ -108,6 +109,7 @@ pub fn create_anthropic_sse_stream_from_responses(
|
||||
let mut index_by_key: HashMap<String, u32> = HashMap::new();
|
||||
let mut open_indices: HashSet<u32> = HashSet::new();
|
||||
let mut fallback_open_index: Option<u32> = None;
|
||||
let mut current_text_index: Option<u32> = None;
|
||||
let mut tool_index_by_item_id: HashMap<String, u32> = HashMap::new();
|
||||
let mut last_tool_index: Option<u32> = None;
|
||||
|
||||
@@ -133,9 +135,9 @@ pub fn create_anthropic_sse_stream_from_responses(
|
||||
let mut data_parts: Vec<String> = Vec::new();
|
||||
|
||||
for line in block.lines() {
|
||||
if let Some(evt) = line.strip_prefix("event: ") {
|
||||
if let Some(evt) = strip_sse_field(line, "event") {
|
||||
event_type = Some(evt.trim().to_string());
|
||||
} else if let Some(d) = line.strip_prefix("data: ") {
|
||||
} else if let Some(d) = strip_sse_field(line, "data") {
|
||||
data_parts.push(d.to_string());
|
||||
}
|
||||
}
|
||||
@@ -217,12 +219,18 @@ pub fn create_anthropic_sse_stream_from_responses(
|
||||
if let Some(part) = data.get("part") {
|
||||
let part_type = part.get("type").and_then(|t| t.as_str());
|
||||
if matches!(part_type, Some("output_text") | Some("refusal")) {
|
||||
let index = resolve_content_index(
|
||||
&data,
|
||||
&mut next_content_index,
|
||||
&mut index_by_key,
|
||||
&mut fallback_open_index,
|
||||
);
|
||||
let index = if let Some(index) = current_text_index {
|
||||
index
|
||||
} else {
|
||||
let index = resolve_content_index(
|
||||
&data,
|
||||
&mut next_content_index,
|
||||
&mut index_by_key,
|
||||
&mut fallback_open_index,
|
||||
);
|
||||
current_text_index = Some(index);
|
||||
index
|
||||
};
|
||||
|
||||
if open_indices.contains(&index) {
|
||||
continue;
|
||||
@@ -249,12 +257,18 @@ pub fn create_anthropic_sse_stream_from_responses(
|
||||
// ================================================
|
||||
"response.output_text.delta" => {
|
||||
if let Some(delta) = data.get("delta").and_then(|d| d.as_str()) {
|
||||
let index = resolve_content_index(
|
||||
&data,
|
||||
&mut next_content_index,
|
||||
&mut index_by_key,
|
||||
&mut fallback_open_index,
|
||||
);
|
||||
let index = if let Some(index) = current_text_index {
|
||||
index
|
||||
} else {
|
||||
let index = resolve_content_index(
|
||||
&data,
|
||||
&mut next_content_index,
|
||||
&mut index_by_key,
|
||||
&mut fallback_open_index,
|
||||
);
|
||||
current_text_index = Some(index);
|
||||
index
|
||||
};
|
||||
|
||||
if !open_indices.contains(&index) {
|
||||
let start_event = json!({
|
||||
@@ -289,12 +303,18 @@ pub fn create_anthropic_sse_stream_from_responses(
|
||||
// ================================================
|
||||
"response.refusal.delta" => {
|
||||
if let Some(delta) = data.get("delta").and_then(|d| d.as_str()) {
|
||||
let index = resolve_content_index(
|
||||
&data,
|
||||
&mut next_content_index,
|
||||
&mut index_by_key,
|
||||
&mut fallback_open_index,
|
||||
);
|
||||
let index = if let Some(index) = current_text_index {
|
||||
index
|
||||
} else {
|
||||
let index = resolve_content_index(
|
||||
&data,
|
||||
&mut next_content_index,
|
||||
&mut index_by_key,
|
||||
&mut fallback_open_index,
|
||||
);
|
||||
current_text_index = Some(index);
|
||||
index
|
||||
};
|
||||
|
||||
if !open_indices.contains(&index) {
|
||||
let start_event = json!({
|
||||
@@ -328,29 +348,7 @@ pub fn create_anthropic_sse_stream_from_responses(
|
||||
// ================================================
|
||||
// response.content_part.done → content_block_stop
|
||||
// ================================================
|
||||
"response.content_part.done" => {
|
||||
let key = content_part_key(&data);
|
||||
let index = if let Some(k) = key {
|
||||
index_by_key.get(&k).copied()
|
||||
} else {
|
||||
fallback_open_index
|
||||
};
|
||||
if let Some(index) = index {
|
||||
if !open_indices.remove(&index) {
|
||||
continue;
|
||||
}
|
||||
let event = json!({
|
||||
"type": "content_block_stop",
|
||||
"index": index
|
||||
});
|
||||
let sse = format!("event: content_block_stop\ndata: {}\n\n",
|
||||
serde_json::to_string(&event).unwrap_or_default());
|
||||
yield Ok(Bytes::from(sse));
|
||||
if fallback_open_index == Some(index) {
|
||||
fallback_open_index = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
"response.content_part.done" => {}
|
||||
|
||||
// ================================================
|
||||
// response.output_item.added (function_call) → content_block_start (tool_use)
|
||||
@@ -360,6 +358,20 @@ pub fn create_anthropic_sse_stream_from_responses(
|
||||
let item_type = item.get("type").and_then(|t| t.as_str()).unwrap_or("");
|
||||
if item_type == "function_call" {
|
||||
has_tool_use = true;
|
||||
if let Some(index) = current_text_index.take() {
|
||||
if open_indices.remove(&index) {
|
||||
let stop_event = json!({
|
||||
"type": "content_block_stop",
|
||||
"index": index
|
||||
});
|
||||
let stop_sse = format!("event: content_block_stop\ndata: {}\n\n",
|
||||
serde_json::to_string(&stop_event).unwrap_or_default());
|
||||
yield Ok(Bytes::from(stop_sse));
|
||||
}
|
||||
if fallback_open_index == Some(index) {
|
||||
fallback_open_index = None;
|
||||
}
|
||||
}
|
||||
// 确保 message_start 已发送
|
||||
if !has_sent_message_start {
|
||||
let start_event = json!({
|
||||
@@ -520,12 +532,14 @@ pub fn create_anthropic_sse_stream_from_responses(
|
||||
// response.refusal.done → content_block_stop
|
||||
// ================================================
|
||||
"response.refusal.done" => {
|
||||
let key = content_part_key(&data);
|
||||
let index = if let Some(k) = key {
|
||||
index_by_key.get(&k).copied()
|
||||
} else {
|
||||
fallback_open_index
|
||||
};
|
||||
let index = current_text_index.take().or_else(|| {
|
||||
let key = content_part_key(&data);
|
||||
if let Some(k) = key {
|
||||
index_by_key.get(&k).copied()
|
||||
} else {
|
||||
fallback_open_index
|
||||
}
|
||||
});
|
||||
if let Some(index) = index {
|
||||
if !open_indices.remove(&index) {
|
||||
continue;
|
||||
@@ -552,6 +566,20 @@ pub fn create_anthropic_sse_stream_from_responses(
|
||||
.or_else(|| data.get("text"))
|
||||
.and_then(|d| d.as_str())
|
||||
{
|
||||
if let Some(index) = current_text_index.take() {
|
||||
if open_indices.remove(&index) {
|
||||
let stop_event = json!({
|
||||
"type": "content_block_stop",
|
||||
"index": index
|
||||
});
|
||||
let stop_sse = format!("event: content_block_stop\ndata: {}\n\n",
|
||||
serde_json::to_string(&stop_event).unwrap_or_default());
|
||||
yield Ok(Bytes::from(stop_sse));
|
||||
}
|
||||
if fallback_open_index == Some(index) {
|
||||
fallback_open_index = None;
|
||||
}
|
||||
}
|
||||
let index = resolve_content_index(
|
||||
&data,
|
||||
&mut next_content_index,
|
||||
@@ -673,8 +701,23 @@ pub fn create_anthropic_sse_stream_from_responses(
|
||||
|
||||
// Lifecycle events that don't need Anthropic counterparts.
|
||||
// Listed explicitly so new events trigger a match-completeness review.
|
||||
"response.output_text.done"
|
||||
| "response.output_item.done"
|
||||
"response.output_text.done" => {
|
||||
if let Some(index) = current_text_index.take() {
|
||||
if open_indices.remove(&index) {
|
||||
let stop_event = json!({
|
||||
"type": "content_block_stop",
|
||||
"index": index
|
||||
});
|
||||
let stop_sse = format!("event: content_block_stop\ndata: {}\n\n",
|
||||
serde_json::to_string(&stop_event).unwrap_or_default());
|
||||
yield Ok(Bytes::from(stop_sse));
|
||||
}
|
||||
if fallback_open_index == Some(index) {
|
||||
fallback_open_index = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
"response.output_item.done"
|
||||
| "response.in_progress" => {}
|
||||
|
||||
// Any other unknown/future events — silently skip.
|
||||
@@ -757,7 +800,9 @@ mod tests {
|
||||
"data: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\",\"usage\":{\"input_tokens\":12,\"output_tokens\":3}}}\n\n"
|
||||
);
|
||||
|
||||
let upstream = stream::iter(vec![Ok(Bytes::from(input.as_bytes().to_vec()))]);
|
||||
let upstream = stream::iter(vec![Ok::<_, std::io::Error>(Bytes::from(
|
||||
input.as_bytes().to_vec(),
|
||||
))]);
|
||||
let converted = create_anthropic_sse_stream_from_responses(upstream);
|
||||
let chunks: Vec<_> = converted.collect().await;
|
||||
|
||||
@@ -799,7 +844,9 @@ mod tests {
|
||||
"data: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\",\"usage\":{\"input_tokens\":8,\"output_tokens\":4}}}\n\n"
|
||||
);
|
||||
|
||||
let upstream = stream::iter(vec![Ok(Bytes::from(input.as_bytes().to_vec()))]);
|
||||
let upstream = stream::iter(vec![Ok::<_, std::io::Error>(Bytes::from(
|
||||
input.as_bytes().to_vec(),
|
||||
))]);
|
||||
let converted = create_anthropic_sse_stream_from_responses(upstream);
|
||||
let chunks: Vec<_> = converted.collect().await;
|
||||
let merged = chunks
|
||||
@@ -810,7 +857,9 @@ mod tests {
|
||||
let events: Vec<Value> = merged
|
||||
.split("\n\n")
|
||||
.filter_map(|block| {
|
||||
let data = block.lines().find_map(|line| line.strip_prefix("data: "))?;
|
||||
let data = block
|
||||
.lines()
|
||||
.find_map(|line| strip_sse_field(line, "data"))?;
|
||||
serde_json::from_str::<Value>(data).ok()
|
||||
})
|
||||
.collect();
|
||||
@@ -868,7 +917,9 @@ mod tests {
|
||||
"data: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\",\"usage\":{\"input_tokens\":5,\"output_tokens\":10}}}\n\n"
|
||||
);
|
||||
|
||||
let upstream = stream::iter(vec![Ok(Bytes::from(input.as_bytes().to_vec()))]);
|
||||
let upstream = stream::iter(vec![Ok::<_, std::io::Error>(Bytes::from(
|
||||
input.as_bytes().to_vec(),
|
||||
))]);
|
||||
let converted = create_anthropic_sse_stream_from_responses(upstream);
|
||||
let chunks: Vec<_> = converted.collect().await;
|
||||
let merged = chunks
|
||||
@@ -899,4 +950,83 @@ mod tests {
|
||||
);
|
||||
assert!(merged.contains("\"stop_reason\":\"end_turn\""));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_streaming_text_parts_are_merged_into_one_text_block() {
|
||||
let input = concat!(
|
||||
"event: response.created\n",
|
||||
"data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_merge\",\"model\":\"gpt-5.4\",\"usage\":{\"input_tokens\":5,\"output_tokens\":0}}}\n\n",
|
||||
"event: response.content_part.added\n",
|
||||
"data: {\"type\":\"response.content_part.added\",\"part\":{\"type\":\"output_text\",\"text\":\"\"},\"output_index\":0,\"content_index\":0}\n\n",
|
||||
"event: response.output_text.delta\n",
|
||||
"data: {\"type\":\"response.output_text.delta\",\"delta\":\"你\",\"output_index\":0,\"content_index\":0}\n\n",
|
||||
"event: response.content_part.done\n",
|
||||
"data: {\"type\":\"response.content_part.done\",\"output_index\":0,\"content_index\":0}\n\n",
|
||||
"event: response.content_part.added\n",
|
||||
"data: {\"type\":\"response.content_part.added\",\"part\":{\"type\":\"output_text\",\"text\":\"\"},\"output_index\":0,\"content_index\":1}\n\n",
|
||||
"event: response.output_text.delta\n",
|
||||
"data: {\"type\":\"response.output_text.delta\",\"delta\":\"好\",\"output_index\":0,\"content_index\":1}\n\n",
|
||||
"event: response.content_part.done\n",
|
||||
"data: {\"type\":\"response.content_part.done\",\"output_index\":0,\"content_index\":1}\n\n",
|
||||
"event: response.output_text.done\n",
|
||||
"data: {\"type\":\"response.output_text.done\",\"output_index\":0,\"content_index\":1}\n\n",
|
||||
"event: response.completed\n",
|
||||
"data: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\",\"usage\":{\"input_tokens\":5,\"output_tokens\":2}}}\n\n"
|
||||
);
|
||||
|
||||
let upstream = stream::iter(vec![Ok::<_, std::io::Error>(Bytes::from(
|
||||
input.as_bytes().to_vec(),
|
||||
))]);
|
||||
let converted = create_anthropic_sse_stream_from_responses(upstream);
|
||||
let chunks: Vec<_> = converted.collect().await;
|
||||
let events: Vec<Value> = chunks
|
||||
.into_iter()
|
||||
.flat_map(|chunk| {
|
||||
let bytes = chunk.unwrap();
|
||||
let text = String::from_utf8_lossy(bytes.as_ref()).to_string();
|
||||
text.split("\n\n")
|
||||
.filter_map(|block| {
|
||||
block.lines().find_map(|line| {
|
||||
strip_sse_field(line, "data")
|
||||
.and_then(|payload| serde_json::from_str::<Value>(payload).ok())
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.collect();
|
||||
|
||||
let text_starts = events
|
||||
.iter()
|
||||
.filter(|event| {
|
||||
event.get("type").and_then(|v| v.as_str()) == Some("content_block_start")
|
||||
&& event
|
||||
.pointer("/content_block/type")
|
||||
.and_then(|v| v.as_str())
|
||||
== Some("text")
|
||||
})
|
||||
.count();
|
||||
let text_stops = events
|
||||
.iter()
|
||||
.filter(|event| {
|
||||
event.get("type").and_then(|v| v.as_str()) == Some("content_block_stop")
|
||||
})
|
||||
.count();
|
||||
let text_deltas: Vec<String> = events
|
||||
.iter()
|
||||
.filter(|event| {
|
||||
event.get("type").and_then(|v| v.as_str()) == Some("content_block_delta")
|
||||
&& event.pointer("/delta/type").and_then(|v| v.as_str()) == Some("text_delta")
|
||||
})
|
||||
.filter_map(|event| {
|
||||
event
|
||||
.pointer("/delta/text")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(ToString::to_string)
|
||||
})
|
||||
.collect();
|
||||
|
||||
assert_eq!(text_starts, 1);
|
||||
assert_eq!(text_stops, 1);
|
||||
assert_eq!(text_deltas, vec!["你".to_string(), "好".to_string()]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,71 @@
|
||||
use crate::proxy::error::ProxyError;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
/// Detect OpenAI o-series reasoning models (o1, o3, o4-mini, etc.)
|
||||
/// These models require `max_completion_tokens` instead of `max_tokens`.
|
||||
pub fn is_openai_o_series(model: &str) -> bool {
|
||||
model.len() > 1
|
||||
&& model.starts_with('o')
|
||||
&& model.as_bytes().get(1).is_some_and(|b| b.is_ascii_digit())
|
||||
}
|
||||
|
||||
/// Detect OpenAI models that support reasoning_effort.
|
||||
///
|
||||
/// Supported families:
|
||||
/// - o-series: o1, o3, o4-mini, etc.
|
||||
/// - GPT-5+: gpt-5, gpt-5.1, gpt-5.4, gpt-5-codex, etc.
|
||||
pub fn supports_reasoning_effort(model: &str) -> bool {
|
||||
is_openai_o_series(model)
|
||||
|| model
|
||||
.to_lowercase()
|
||||
.strip_prefix("gpt-")
|
||||
.and_then(|rest| rest.chars().next())
|
||||
.is_some_and(|c| c.is_ascii_digit() && c >= '5')
|
||||
}
|
||||
|
||||
/// Resolve the appropriate OpenAI `reasoning_effort` from an Anthropic request body.
|
||||
///
|
||||
/// Priority:
|
||||
/// 1. Explicit `output_config.effort` — preserves the user's intent directly.
|
||||
/// `low`/`medium`/`high` map 1:1; `max` maps to `xhigh`
|
||||
/// (supported by mainstream GPT models). Unknown values are ignored.
|
||||
/// 2. Fallback: `thinking.type` + `budget_tokens`:
|
||||
/// - `adaptive` → `high` (mirrors optimizer semantics where adaptive ≈ max effort)
|
||||
/// - `enabled` with budget → `low` (<4 000) / `medium` (4 000–15 999) / `high` (≥16 000)
|
||||
/// - `enabled` without budget → `high` (conservative default)
|
||||
/// - `disabled` / absent → `None`
|
||||
pub fn resolve_reasoning_effort(body: &Value) -> Option<&'static str> {
|
||||
// --- Priority 1: explicit output_config.effort ---
|
||||
if let Some(effort) = body
|
||||
.pointer("/output_config/effort")
|
||||
.and_then(|v| v.as_str())
|
||||
{
|
||||
return match effort {
|
||||
"low" => Some("low"),
|
||||
"medium" => Some("medium"),
|
||||
"high" => Some("high"),
|
||||
"max" => Some("xhigh"), // OpenAI xhigh = maximum reasoning effort
|
||||
_ => None, // unknown value — do not inject
|
||||
};
|
||||
}
|
||||
|
||||
// --- Priority 2: thinking.type + budget_tokens fallback ---
|
||||
let thinking = body.get("thinking")?;
|
||||
match thinking.get("type").and_then(|t| t.as_str()) {
|
||||
Some("adaptive") => Some("high"),
|
||||
Some("enabled") => {
|
||||
let budget = thinking.get("budget_tokens").and_then(|b| b.as_u64());
|
||||
match budget {
|
||||
Some(b) if b < 4_000 => Some("low"),
|
||||
Some(b) if b < 16_000 => Some("medium"),
|
||||
Some(_) => Some("high"),
|
||||
None => Some("high"), // enabled but no budget — assume strong reasoning
|
||||
}
|
||||
}
|
||||
_ => None, // disabled or missing
|
||||
}
|
||||
}
|
||||
|
||||
/// Anthropic 请求 → OpenAI 请求
|
||||
///
|
||||
/// `cache_key`: optional prompt_cache_key to inject for improved cache routing
|
||||
@@ -50,9 +115,14 @@ pub fn anthropic_to_openai(body: Value, cache_key: Option<&str>) -> Result<Value
|
||||
|
||||
result["messages"] = json!(messages);
|
||||
|
||||
// 转换参数
|
||||
// 转换参数 — o-series 模型需要 max_completion_tokens
|
||||
let model = body.get("model").and_then(|m| m.as_str()).unwrap_or("");
|
||||
if let Some(v) = body.get("max_tokens") {
|
||||
result["max_tokens"] = v.clone();
|
||||
if is_openai_o_series(model) {
|
||||
result["max_completion_tokens"] = v.clone();
|
||||
} else {
|
||||
result["max_tokens"] = v.clone();
|
||||
}
|
||||
}
|
||||
if let Some(v) = body.get("temperature") {
|
||||
result["temperature"] = v.clone();
|
||||
@@ -67,6 +137,13 @@ pub fn anthropic_to_openai(body: Value, cache_key: Option<&str>) -> Result<Value
|
||||
result["stream"] = v.clone();
|
||||
}
|
||||
|
||||
// Map Anthropic thinking → OpenAI reasoning_effort
|
||||
if supports_reasoning_effort(model) {
|
||||
if let Some(effort) = resolve_reasoning_effort(&body) {
|
||||
result["reasoning_effort"] = json!(effort);
|
||||
}
|
||||
}
|
||||
|
||||
// 转换 tools (过滤 BatchTool)
|
||||
if let Some(tools) = body.get("tools").and_then(|t| t.as_array()) {
|
||||
let openai_tools: Vec<Value> = tools
|
||||
@@ -772,4 +849,226 @@ mod tests {
|
||||
assert_eq!(result["content"][1]["type"], "text");
|
||||
assert_eq!(result["content"][1]["text"], "I can't do that");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_openai_o_series() {
|
||||
assert!(is_openai_o_series("o1"));
|
||||
assert!(is_openai_o_series("o1-preview"));
|
||||
assert!(is_openai_o_series("o1-mini"));
|
||||
assert!(is_openai_o_series("o3"));
|
||||
assert!(is_openai_o_series("o3-mini"));
|
||||
assert!(is_openai_o_series("o4-mini"));
|
||||
assert!(!is_openai_o_series("gpt-4o"));
|
||||
assert!(!is_openai_o_series("openai-gpt"));
|
||||
assert!(!is_openai_o_series("o"));
|
||||
assert!(!is_openai_o_series(""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_supports_reasoning_effort() {
|
||||
assert!(supports_reasoning_effort("o1"));
|
||||
assert!(supports_reasoning_effort("o3-mini"));
|
||||
assert!(supports_reasoning_effort("gpt-5"));
|
||||
assert!(supports_reasoning_effort("gpt-5.4"));
|
||||
assert!(supports_reasoning_effort("gpt-5-codex"));
|
||||
assert!(!supports_reasoning_effort("gpt-4o"));
|
||||
assert!(!supports_reasoning_effort("claude-sonnet-4-6"));
|
||||
}
|
||||
|
||||
// ── resolve_reasoning_effort unit tests ──
|
||||
|
||||
#[test]
|
||||
fn test_output_config_low_maps_to_reasoning_effort_low() {
|
||||
let body = json!({"output_config": {"effort": "low"}});
|
||||
assert_eq!(resolve_reasoning_effort(&body), Some("low"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_output_config_medium_maps_to_reasoning_effort_medium() {
|
||||
let body = json!({"output_config": {"effort": "medium"}});
|
||||
assert_eq!(resolve_reasoning_effort(&body), Some("medium"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_output_config_high_maps_to_reasoning_effort_high() {
|
||||
let body = json!({"output_config": {"effort": "high"}});
|
||||
assert_eq!(resolve_reasoning_effort(&body), Some("high"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_output_config_max_maps_to_reasoning_effort_xhigh() {
|
||||
let body = json!({"output_config": {"effort": "max"}});
|
||||
assert_eq!(resolve_reasoning_effort(&body), Some("xhigh"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_output_config_takes_priority_over_thinking() {
|
||||
// Even with thinking.adaptive present, explicit effort wins
|
||||
let body = json!({
|
||||
"output_config": {"effort": "low"},
|
||||
"thinking": {"type": "adaptive"}
|
||||
});
|
||||
assert_eq!(resolve_reasoning_effort(&body), Some("low"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_output_config_unknown_value_no_reasoning_effort() {
|
||||
let body = json!({"output_config": {"effort": "turbo"}});
|
||||
assert_eq!(resolve_reasoning_effort(&body), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_thinking_enabled_small_budget_maps_low() {
|
||||
let body = json!({"thinking": {"type": "enabled", "budget_tokens": 1024}});
|
||||
assert_eq!(resolve_reasoning_effort(&body), Some("low"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_thinking_enabled_medium_budget_maps_medium() {
|
||||
let body = json!({"thinking": {"type": "enabled", "budget_tokens": 8000}});
|
||||
assert_eq!(resolve_reasoning_effort(&body), Some("medium"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_thinking_enabled_large_budget_maps_high() {
|
||||
let body = json!({"thinking": {"type": "enabled", "budget_tokens": 32000}});
|
||||
assert_eq!(resolve_reasoning_effort(&body), Some("high"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_thinking_enabled_without_budget_maps_high() {
|
||||
let body = json!({"thinking": {"type": "enabled"}});
|
||||
assert_eq!(resolve_reasoning_effort(&body), Some("high"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_thinking_adaptive_maps_high() {
|
||||
let body = json!({"thinking": {"type": "adaptive"}});
|
||||
assert_eq!(resolve_reasoning_effort(&body), Some("high"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_thinking_disabled_no_reasoning_effort() {
|
||||
let body = json!({"thinking": {"type": "disabled"}});
|
||||
assert_eq!(resolve_reasoning_effort(&body), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_thinking_field_no_reasoning_effort() {
|
||||
let body = json!({"messages": [{"role": "user", "content": "Hello"}]});
|
||||
assert_eq!(resolve_reasoning_effort(&body), None);
|
||||
}
|
||||
|
||||
// ── Integration: anthropic_to_openai with resolve_reasoning_effort ──
|
||||
|
||||
#[test]
|
||||
fn test_non_reasoning_model_no_reasoning_effort() {
|
||||
let input = json!({
|
||||
"model": "gpt-4o",
|
||||
"max_tokens": 1024,
|
||||
"thinking": {"type": "enabled", "budget_tokens": 2048},
|
||||
"messages": [{"role": "user", "content": "Hello"}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_openai(input, None).unwrap();
|
||||
assert!(result.get("reasoning_effort").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reasoning_model_with_output_config_effort() {
|
||||
let input = json!({
|
||||
"model": "gpt-5.4",
|
||||
"max_tokens": 1024,
|
||||
"output_config": {"effort": "medium"},
|
||||
"messages": [{"role": "user", "content": "Hello"}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_openai(input, None).unwrap();
|
||||
assert_eq!(result["reasoning_effort"], "medium");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reasoning_model_with_output_config_max() {
|
||||
let input = json!({
|
||||
"model": "gpt-5.4",
|
||||
"max_tokens": 1024,
|
||||
"output_config": {"effort": "max"},
|
||||
"messages": [{"role": "user", "content": "Hello"}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_openai(input, None).unwrap();
|
||||
assert_eq!(result["reasoning_effort"], "xhigh");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reasoning_model_thinking_enabled_small_budget() {
|
||||
let input = json!({
|
||||
"model": "o3",
|
||||
"max_tokens": 1024,
|
||||
"thinking": {"type": "enabled", "budget_tokens": 2048},
|
||||
"messages": [{"role": "user", "content": "Hello"}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_openai(input, None).unwrap();
|
||||
assert_eq!(result["reasoning_effort"], "low");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reasoning_model_thinking_adaptive() {
|
||||
let input = json!({
|
||||
"model": "gpt-5.4",
|
||||
"max_tokens": 1024,
|
||||
"thinking": {"type": "adaptive"},
|
||||
"messages": [{"role": "user", "content": "Hello"}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_openai(input, None).unwrap();
|
||||
assert_eq!(result["reasoning_effort"], "high");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reasoning_model_no_thinking_no_effort() {
|
||||
let input = json!({
|
||||
"model": "gpt-5.4",
|
||||
"max_tokens": 1024,
|
||||
"messages": [{"role": "user", "content": "Hello"}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_openai(input, None).unwrap();
|
||||
assert!(result.get("reasoning_effort").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_to_openai_o_series_max_completion_tokens() {
|
||||
for model in &["o1", "o3-mini", "o4-mini"] {
|
||||
let input = json!({
|
||||
"model": model,
|
||||
"max_tokens": 4096,
|
||||
"messages": [{"role": "user", "content": "Hello"}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_openai(input, None).unwrap();
|
||||
assert!(
|
||||
result.get("max_tokens").is_none(),
|
||||
"{model} should not have max_tokens"
|
||||
);
|
||||
assert_eq!(
|
||||
result["max_completion_tokens"], 4096,
|
||||
"{model} should use max_completion_tokens"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_to_openai_non_o_series_keeps_max_tokens() {
|
||||
let input = json!({
|
||||
"model": "gpt-4o",
|
||||
"max_tokens": 1024,
|
||||
"messages": [{"role": "user", "content": "Hello"}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_openai(input, None).unwrap();
|
||||
assert_eq!(result["max_tokens"], 1024);
|
||||
assert!(result.get("max_completion_tokens").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ pub fn anthropic_to_responses(body: Value, cache_key: Option<&str>) -> Result<Va
|
||||
result["input"] = json!(input);
|
||||
}
|
||||
|
||||
// max_tokens → max_output_tokens
|
||||
// max_tokens → max_output_tokens (Responses API uses max_output_tokens for all models)
|
||||
if let Some(v) = body.get("max_tokens") {
|
||||
result["max_output_tokens"] = v.clone();
|
||||
}
|
||||
@@ -61,6 +61,15 @@ pub fn anthropic_to_responses(body: Value, cache_key: Option<&str>) -> Result<Va
|
||||
result["stream"] = v.clone();
|
||||
}
|
||||
|
||||
// Map Anthropic thinking → OpenAI Responses reasoning.effort
|
||||
if let Some(model_name) = body.get("model").and_then(|m| m.as_str()) {
|
||||
if super::transform::supports_reasoning_effort(model_name) {
|
||||
if let Some(effort) = super::transform::resolve_reasoning_effort(&body) {
|
||||
result["reasoning"] = json!({ "effort": effort });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// stop_sequences → 丢弃 (Responses API 不支持)
|
||||
|
||||
// 转换 tools (过滤 BatchTool)
|
||||
@@ -897,4 +906,109 @@ mod tests {
|
||||
assert_eq!(result["usage"]["cache_read_input_tokens"], 60);
|
||||
assert_eq!(result["usage"]["cache_creation_input_tokens"], 20);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_to_responses_o_series_uses_max_output_tokens() {
|
||||
// Responses API always uses max_output_tokens, even for o-series models
|
||||
let input = json!({
|
||||
"model": "o3-mini",
|
||||
"max_tokens": 4096,
|
||||
"messages": [{"role": "user", "content": "Hello"}]
|
||||
});
|
||||
let result = anthropic_to_responses(input, None).unwrap();
|
||||
assert_eq!(result["max_output_tokens"], 4096);
|
||||
assert!(result.get("max_completion_tokens").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_responses_output_config_max_sets_reasoning_xhigh() {
|
||||
let input = json!({
|
||||
"model": "gpt-5.4",
|
||||
"max_tokens": 1024,
|
||||
"output_config": {"effort": "max"},
|
||||
"messages": [{"role": "user", "content": "Hello"}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_responses(input, None).unwrap();
|
||||
assert_eq!(result["reasoning"]["effort"], "xhigh");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_responses_output_config_takes_priority_over_thinking() {
|
||||
let input = json!({
|
||||
"model": "gpt-5.4",
|
||||
"max_tokens": 1024,
|
||||
"output_config": {"effort": "low"},
|
||||
"thinking": {"type": "adaptive"},
|
||||
"messages": [{"role": "user", "content": "Hello"}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_responses(input, None).unwrap();
|
||||
assert_eq!(result["reasoning"]["effort"], "low");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_responses_thinking_enabled_small_budget_sets_reasoning_low() {
|
||||
let input = json!({
|
||||
"model": "gpt-5.4",
|
||||
"max_tokens": 1024,
|
||||
"thinking": {"type": "enabled", "budget_tokens": 2048},
|
||||
"messages": [{"role": "user", "content": "Hello"}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_responses(input, None).unwrap();
|
||||
assert_eq!(result["reasoning"]["effort"], "low");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_responses_thinking_enabled_medium_budget_sets_reasoning_medium() {
|
||||
let input = json!({
|
||||
"model": "gpt-5.4",
|
||||
"max_tokens": 1024,
|
||||
"thinking": {"type": "enabled", "budget_tokens": 8000},
|
||||
"messages": [{"role": "user", "content": "Hello"}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_responses(input, None).unwrap();
|
||||
assert_eq!(result["reasoning"]["effort"], "medium");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_responses_thinking_enabled_large_budget_sets_reasoning_high() {
|
||||
let input = json!({
|
||||
"model": "gpt-5.4",
|
||||
"max_tokens": 1024,
|
||||
"thinking": {"type": "enabled", "budget_tokens": 32000},
|
||||
"messages": [{"role": "user", "content": "Hello"}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_responses(input, None).unwrap();
|
||||
assert_eq!(result["reasoning"]["effort"], "high");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_responses_thinking_adaptive_sets_reasoning_high() {
|
||||
let input = json!({
|
||||
"model": "gpt-5.4",
|
||||
"max_tokens": 1024,
|
||||
"thinking": {"type": "adaptive"},
|
||||
"messages": [{"role": "user", "content": "Hello"}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_responses(input, None).unwrap();
|
||||
assert_eq!(result["reasoning"]["effort"], "high");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_responses_non_reasoning_model_no_reasoning() {
|
||||
let input = json!({
|
||||
"model": "gpt-4o",
|
||||
"max_tokens": 1024,
|
||||
"thinking": {"type": "enabled", "budget_tokens": 2048},
|
||||
"messages": [{"role": "user", "content": "Hello"}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_responses(input, None).unwrap();
|
||||
assert!(result.get("reasoning").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
use super::session::ProxySession;
|
||||
use super::usage::parser::TokenUsage;
|
||||
use super::ProxyError;
|
||||
use crate::proxy::sse::strip_sse_field;
|
||||
use bytes::Bytes;
|
||||
use futures::stream::{Stream, StreamExt};
|
||||
use serde_json::Value;
|
||||
@@ -90,7 +91,7 @@ impl StreamHandler {
|
||||
buffer = buffer[pos + 2..].to_string();
|
||||
|
||||
for line in event_text.lines() {
|
||||
if let Some(data) = line.strip_prefix("data: ") {
|
||||
if let Some(data) = strip_sse_field(line, "data") {
|
||||
if data.trim() != "[DONE]" {
|
||||
if let Ok(json) = serde_json::from_str::<Value>(data) {
|
||||
let mut guard = events.lock().await;
|
||||
@@ -211,4 +212,24 @@ mod tests {
|
||||
let handler = StreamHandler::new(30);
|
||||
assert_eq!(handler.idle_timeout, Duration::from_secs(30));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strip_sse_field_accepts_optional_space() {
|
||||
assert_eq!(
|
||||
super::strip_sse_field("data: {\"ok\":true}", "data"),
|
||||
Some("{\"ok\":true}")
|
||||
);
|
||||
assert_eq!(
|
||||
super::strip_sse_field("data:{\"ok\":true}", "data"),
|
||||
Some("{\"ok\":true}")
|
||||
);
|
||||
assert_eq!(
|
||||
super::strip_sse_field("event: message_start", "event"),
|
||||
Some("message_start")
|
||||
);
|
||||
assert_eq!(
|
||||
super::strip_sse_field("event:message_start", "event"),
|
||||
Some("message_start")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,16 +5,19 @@
|
||||
use super::{
|
||||
handler_config::UsageParserConfig,
|
||||
handler_context::{RequestContext, StreamingTimeoutConfig},
|
||||
hyper_client::ProxyResponse,
|
||||
server::ProxyState,
|
||||
sse::strip_sse_field,
|
||||
usage::parser::TokenUsage,
|
||||
ProxyError,
|
||||
};
|
||||
use axum::http::header::HeaderMap;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use bytes::Bytes;
|
||||
use futures::stream::{Stream, StreamExt};
|
||||
use reqwest::header::HeaderMap;
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
io::Read,
|
||||
sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
@@ -23,24 +26,123 @@ use std::{
|
||||
};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
// ============================================================================
|
||||
// 响应解压
|
||||
// ============================================================================
|
||||
|
||||
/// 根据 content-encoding 解压响应体字节
|
||||
///
|
||||
/// reqwest 自动解压已禁用(为了透传 accept-encoding),需要手动解压。
|
||||
fn decompress_body(content_encoding: &str, body: &[u8]) -> Result<Vec<u8>, std::io::Error> {
|
||||
match content_encoding {
|
||||
"gzip" | "x-gzip" => {
|
||||
let mut decoder = flate2::read::GzDecoder::new(body);
|
||||
let mut decompressed = Vec::new();
|
||||
decoder.read_to_end(&mut decompressed)?;
|
||||
Ok(decompressed)
|
||||
}
|
||||
"deflate" => {
|
||||
let mut decoder = flate2::read::DeflateDecoder::new(body);
|
||||
let mut decompressed = Vec::new();
|
||||
decoder.read_to_end(&mut decompressed)?;
|
||||
Ok(decompressed)
|
||||
}
|
||||
"br" => {
|
||||
let mut decompressed = Vec::new();
|
||||
brotli::BrotliDecompress(&mut std::io::Cursor::new(body), &mut decompressed)?;
|
||||
Ok(decompressed)
|
||||
}
|
||||
_ => {
|
||||
log::warn!("未知的 content-encoding: {content_encoding},跳过解压");
|
||||
Ok(body.to_vec())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 从响应头提取 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")
|
||||
}
|
||||
|
||||
/// 移除在重建响应体后会失真的实体头。
|
||||
pub(crate) fn strip_entity_headers_for_rebuilt_body(headers: &mut HeaderMap) {
|
||||
headers.remove(axum::http::header::CONTENT_ENCODING);
|
||||
headers.remove(axum::http::header::CONTENT_LENGTH);
|
||||
headers.remove(axum::http::header::TRANSFER_ENCODING);
|
||||
}
|
||||
|
||||
/// 读取响应体并在需要时解压,确保 headers 与返回 body 一致。
|
||||
///
|
||||
/// `body_timeout`: 整包超时。当非零时用 `tokio::time::timeout` 包住 `.bytes()` 调用,
|
||||
/// 防止上游发完响应头后卡住 body 导致请求永远挂住。
|
||||
/// 传入 `Duration::ZERO` 表示不启用超时(故障转移关闭时)。
|
||||
pub(crate) async fn read_decoded_body(
|
||||
response: ProxyResponse,
|
||||
tag: &str,
|
||||
body_timeout: Duration,
|
||||
) -> Result<(HeaderMap, http::StatusCode, Bytes), ProxyError> {
|
||||
let mut headers = response.headers().clone();
|
||||
let status = response.status();
|
||||
let raw_bytes = if body_timeout.is_zero() {
|
||||
response.bytes().await?
|
||||
} else {
|
||||
tokio::time::timeout(body_timeout, response.bytes())
|
||||
.await
|
||||
.map_err(|_| {
|
||||
ProxyError::Timeout(format!(
|
||||
"响应体读取超时: {}s(上游发完响应头后 body 未到达)",
|
||||
body_timeout.as_secs()
|
||||
))
|
||||
})??
|
||||
};
|
||||
|
||||
log::debug!(
|
||||
"[{tag}] 已接收上游响应体: status={}, bytes={}, headers={}",
|
||||
status.as_u16(),
|
||||
raw_bytes.len(),
|
||||
format_headers(&headers)
|
||||
);
|
||||
|
||||
let mut body_bytes = raw_bytes.clone();
|
||||
let mut decoded = false;
|
||||
|
||||
if let Some(encoding) = get_content_encoding(&headers) {
|
||||
log::debug!("[{tag}] 解压非流式响应: content-encoding={encoding}");
|
||||
match decompress_body(&encoding, &raw_bytes) {
|
||||
Ok(decompressed) => {
|
||||
body_bytes = Bytes::from(decompressed);
|
||||
decoded = true;
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("[{tag}] 解压失败 ({encoding}): {e},使用原始数据");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if decoded {
|
||||
strip_entity_headers_for_rebuilt_body(&mut headers);
|
||||
}
|
||||
|
||||
Ok((headers, status, body_bytes))
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 公共接口
|
||||
// ============================================================================
|
||||
|
||||
/// 检测响应是否为 SSE 流式响应
|
||||
#[inline]
|
||||
pub fn is_sse_response(response: &reqwest::Response) -> bool {
|
||||
response
|
||||
.headers()
|
||||
.get("content-type")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(|ct| ct.contains("text/event-stream"))
|
||||
.unwrap_or(false)
|
||||
pub fn is_sse_response(response: &ProxyResponse) -> bool {
|
||||
response.is_sse()
|
||||
}
|
||||
|
||||
/// 处理流式响应
|
||||
pub async fn handle_streaming(
|
||||
response: reqwest::Response,
|
||||
response: ProxyResponse,
|
||||
ctx: &RequestContext,
|
||||
state: &ProxyState,
|
||||
parser_config: &UsageParserConfig,
|
||||
@@ -52,6 +154,15 @@ pub async fn handle_streaming(
|
||||
status.as_u16(),
|
||||
format_headers(response.headers())
|
||||
);
|
||||
// 检查流式响应是否被压缩(SSE 通常不压缩,如果压缩则 SSE 解析会失败)
|
||||
if let Some(encoding) = get_content_encoding(response.headers()) {
|
||||
log::warn!(
|
||||
"[{}] 流式响应含 content-encoding={encoding},SSE 解析可能失败。\
|
||||
上游在 accept-encoding 透传后压缩了 SSE 流。",
|
||||
ctx.tag
|
||||
);
|
||||
}
|
||||
|
||||
let mut builder = axum::response::Response::builder().status(status);
|
||||
|
||||
// 复制响应头
|
||||
@@ -60,9 +171,7 @@ pub async fn handle_streaming(
|
||||
}
|
||||
|
||||
// 创建字节流
|
||||
let stream = response
|
||||
.bytes_stream()
|
||||
.map(|chunk| chunk.map_err(|e| std::io::Error::other(e.to_string())));
|
||||
let stream = response.bytes_stream();
|
||||
|
||||
// 创建使用量收集器
|
||||
let usage_collector = create_usage_collector(ctx, state, status.as_u16(), parser_config);
|
||||
@@ -86,26 +195,20 @@ pub async fn handle_streaming(
|
||||
|
||||
/// 处理非流式响应
|
||||
pub async fn handle_non_streaming(
|
||||
response: reqwest::Response,
|
||||
response: ProxyResponse,
|
||||
ctx: &RequestContext,
|
||||
state: &ProxyState,
|
||||
parser_config: &UsageParserConfig,
|
||||
) -> Result<Response, ProxyError> {
|
||||
let response_headers = response.headers().clone();
|
||||
let status = response.status();
|
||||
|
||||
// 读取响应体
|
||||
let body_bytes = response.bytes().await.map_err(|e| {
|
||||
log::error!("[{}] 读取响应失败: {e}", ctx.tag);
|
||||
ProxyError::ForwardFailed(format!("Failed to read response body: {e}"))
|
||||
})?;
|
||||
log::debug!(
|
||||
"[{}] 已接收上游响应体: status={}, bytes={}, headers={}",
|
||||
ctx.tag,
|
||||
status.as_u16(),
|
||||
body_bytes.len(),
|
||||
format_headers(&response_headers)
|
||||
);
|
||||
// 整包超时:仅在故障转移开启且配置值非零时生效
|
||||
let body_timeout =
|
||||
if ctx.app_config.auto_failover_enabled && ctx.app_config.non_streaming_timeout > 0 {
|
||||
Duration::from_secs(ctx.app_config.non_streaming_timeout as u64)
|
||||
} else {
|
||||
Duration::ZERO
|
||||
};
|
||||
let (response_headers, status, body_bytes) =
|
||||
read_decoded_body(response, ctx.tag, body_timeout).await?;
|
||||
|
||||
log::debug!(
|
||||
"[{}] 上游响应体内容: {}",
|
||||
@@ -189,7 +292,7 @@ pub async fn handle_non_streaming(
|
||||
///
|
||||
/// 根据响应类型自动选择流式或非流式处理
|
||||
pub async fn process_response(
|
||||
response: reqwest::Response,
|
||||
response: ProxyResponse,
|
||||
ctx: &RequestContext,
|
||||
state: &ProxyState,
|
||||
parser_config: &UsageParserConfig,
|
||||
@@ -527,7 +630,7 @@ pub fn create_logged_passthrough_stream(
|
||||
if !event_text.trim().is_empty() {
|
||||
// 提取 data 部分并尝试解析为 JSON
|
||||
for line in event_text.lines() {
|
||||
if let Some(data) = line.strip_prefix("data: ") {
|
||||
if let Some(data) = strip_sse_field(line, "data") {
|
||||
if data.trim() != "[DONE]" {
|
||||
if let Ok(json_value) = serde_json::from_str::<Value>(data) {
|
||||
if let Some(c) = &collector {
|
||||
@@ -591,6 +694,27 @@ mod tests {
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
#[test]
|
||||
fn test_strip_sse_field_accepts_optional_space() {
|
||||
assert_eq!(
|
||||
super::strip_sse_field("data: {\"ok\":true}", "data"),
|
||||
Some("{\"ok\":true}")
|
||||
);
|
||||
assert_eq!(
|
||||
super::strip_sse_field("data:{\"ok\":true}", "data"),
|
||||
Some("{\"ok\":true}")
|
||||
);
|
||||
assert_eq!(
|
||||
super::strip_sse_field("event: message_start", "event"),
|
||||
Some("message_start")
|
||||
);
|
||||
assert_eq!(
|
||||
super::strip_sse_field("event:message_start", "event"),
|
||||
Some("message_start")
|
||||
);
|
||||
assert_eq!(super::strip_sse_field("id:1", "data"), None);
|
||||
}
|
||||
|
||||
fn build_state(db: Arc<Database>) -> ProxyState {
|
||||
ProxyState {
|
||||
db: db.clone(),
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
//! HTTP代理服务器
|
||||
//!
|
||||
//! 基于Axum的HTTP服务器,处理代理请求
|
||||
//!
|
||||
//! Uses a manual hyper HTTP/1.1 accept loop with `preserve_header_case(true)` so
|
||||
//! that the original header-name casing from the CLI client is captured in a
|
||||
//! `HeaderCaseMap` extension. This map is later forwarded to the upstream via
|
||||
//! the hyper-based HTTP client, producing wire-level header casing identical to
|
||||
//! a direct (non-proxied) CLI request.
|
||||
|
||||
use super::{
|
||||
failover_switch::FailoverSwitchManager, handlers, log_codes::srv as log_srv,
|
||||
@@ -12,6 +18,7 @@ use axum::{
|
||||
routing::{get, post},
|
||||
Router,
|
||||
};
|
||||
use hyper_util::rt::TokioIo;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::{oneshot, RwLock};
|
||||
@@ -114,15 +121,77 @@ impl ProxyServer {
|
||||
// 记录启动时间
|
||||
*self.state.start_time.write().await = Some(std::time::Instant::now());
|
||||
|
||||
// 启动服务器
|
||||
// 启动服务器 — 使用手动 hyper HTTP/1.1 accept loop
|
||||
// 开启 preserve_header_case 以捕获客户端请求头的原始大小写
|
||||
let state = self.state.clone();
|
||||
let handle = tokio::spawn(async move {
|
||||
axum::serve(listener, app)
|
||||
.with_graceful_shutdown(async {
|
||||
shutdown_rx.await.ok();
|
||||
})
|
||||
.await
|
||||
.ok();
|
||||
let mut shutdown_rx = shutdown_rx;
|
||||
loop {
|
||||
tokio::select! {
|
||||
result = listener.accept() => {
|
||||
let (stream, _remote_addr) = match result {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
log::error!("[{SRV}] accept 失败: {e}", SRV = log_srv::ACCEPT_ERR);
|
||||
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let app = app.clone();
|
||||
tokio::spawn(async move {
|
||||
// Peek raw TCP bytes to capture original header casing
|
||||
// before hyper parses (and lowercases) the header names.
|
||||
let original_cases = {
|
||||
let mut peek_buf = vec![0u8; 8192];
|
||||
match stream.peek(&mut peek_buf).await {
|
||||
Ok(n) => {
|
||||
let cases = super::hyper_client::OriginalHeaderCases::from_raw_bytes(&peek_buf[..n]);
|
||||
log::debug!(
|
||||
"[ProxyServer] Peeked {} bytes, captured {} header casings",
|
||||
n, cases.cases.len()
|
||||
);
|
||||
cases
|
||||
}
|
||||
Err(e) => {
|
||||
log::debug!("[ProxyServer] peek failed (non-fatal): {e}");
|
||||
super::hyper_client::OriginalHeaderCases::default()
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// service_fn 将 axum Router(tower::Service)桥接到 hyper
|
||||
let service = hyper::service::service_fn(move |req: hyper::Request<hyper::body::Incoming>| {
|
||||
let mut router = app.clone();
|
||||
let cases = original_cases.clone();
|
||||
async move {
|
||||
// 将 hyper::body::Incoming 转为 axum::body::Body,保留 extensions
|
||||
let (mut parts, body) = req.into_parts();
|
||||
|
||||
// Insert our own header case map alongside hyper's internal one
|
||||
parts.extensions.insert(cases);
|
||||
|
||||
let body = axum::body::Body::new(body);
|
||||
let axum_req = http::Request::from_parts(parts, body);
|
||||
<Router as tower::Service<http::Request<axum::body::Body>>>::call(&mut router, axum_req).await
|
||||
}
|
||||
});
|
||||
|
||||
if let Err(e) = hyper::server::conn::http1::Builder::new()
|
||||
.preserve_header_case(true)
|
||||
.serve_connection(TokioIo::new(stream), service)
|
||||
.await
|
||||
{
|
||||
// Connection reset / broken pipe 等在代理场景下很常见,debug 级别
|
||||
log::debug!("[{SRV}] connection error: {e}", SRV = log_srv::CONN_ERR);
|
||||
}
|
||||
});
|
||||
}
|
||||
_ = &mut shutdown_rx => {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 服务器停止后更新状态
|
||||
state.status.write().await.running = false;
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
#[inline]
|
||||
pub(crate) fn strip_sse_field<'a>(line: &'a str, field: &str) -> Option<&'a str> {
|
||||
line.strip_prefix(&format!("{field}: "))
|
||||
.or_else(|| line.strip_prefix(&format!("{field}:")))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::strip_sse_field;
|
||||
|
||||
#[test]
|
||||
fn strip_sse_field_accepts_optional_space() {
|
||||
assert_eq!(
|
||||
strip_sse_field("data: {\"ok\":true}", "data"),
|
||||
Some("{\"ok\":true}")
|
||||
);
|
||||
assert_eq!(
|
||||
strip_sse_field("data:{\"ok\":true}", "data"),
|
||||
Some("{\"ok\":true}")
|
||||
);
|
||||
assert_eq!(
|
||||
strip_sse_field("event: message_start", "event"),
|
||||
Some("message_start")
|
||||
);
|
||||
assert_eq!(
|
||||
strip_sse_field("event:message_start", "event"),
|
||||
Some("message_start")
|
||||
);
|
||||
assert_eq!(strip_sse_field("id:1", "data"), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
//! Per-app switch lock
|
||||
//!
|
||||
//! 确保同一应用同时只有一个供应商切换操作在执行,
|
||||
//! 防止并发切换导致 is_current 与 Live 备份不一致。
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::{Mutex, OwnedMutexGuard, RwLock};
|
||||
|
||||
/// 每个应用类型一把互斥锁,保证同一应用的切换操作串行执行。
|
||||
///
|
||||
/// 不同应用之间(如 Claude 和 Codex)可以并行切换。
|
||||
#[derive(Clone, Default)]
|
||||
pub struct SwitchLockManager {
|
||||
locks: Arc<RwLock<HashMap<String, Arc<Mutex<()>>>>>,
|
||||
}
|
||||
|
||||
impl SwitchLockManager {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// 获取指定应用的切换锁。
|
||||
///
|
||||
/// 返回 `OwnedMutexGuard`,持有期间同一 `app_type` 的其他切换会排队等待。
|
||||
pub async fn lock_for_app(&self, app_type: &str) -> OwnedMutexGuard<()> {
|
||||
let lock = {
|
||||
let locks = self.locks.read().await;
|
||||
if let Some(lock) = locks.get(app_type) {
|
||||
lock.clone()
|
||||
} else {
|
||||
drop(locks);
|
||||
let mut locks = self.locks.write().await;
|
||||
locks
|
||||
.entry(app_type.to_string())
|
||||
.or_insert_with(|| Arc::new(Mutex::new(())))
|
||||
.clone()
|
||||
}
|
||||
};
|
||||
lock.lock_owned().await
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ pub fn optimize(body: &mut Value, config: &OptimizerConfig) {
|
||||
}
|
||||
|
||||
if model.contains("opus-4-6") || model.contains("sonnet-4-6") {
|
||||
log::info!("[OPT] thinking: adaptive({})", model);
|
||||
log::info!("[OPT] thinking: adaptive({model})");
|
||||
body["thinking"] = json!({"type": "adaptive"});
|
||||
body["output_config"] = json!({"effort": "max"});
|
||||
append_beta(body, "context-1m-2025-08-07");
|
||||
@@ -33,7 +33,7 @@ pub fn optimize(body: &mut Value, config: &OptimizerConfig) {
|
||||
}
|
||||
|
||||
// legacy path
|
||||
log::info!("[OPT] thinking: legacy({})", model);
|
||||
log::info!("[OPT] thinking: legacy({model})");
|
||||
|
||||
let max_tokens = body
|
||||
.get("max_tokens")
|
||||
|
||||
@@ -165,8 +165,18 @@ impl McpService {
|
||||
pub fn sync_all_enabled(state: &AppState) -> Result<(), AppError> {
|
||||
let servers = Self::get_all_servers(state)?;
|
||||
|
||||
for server in servers.values() {
|
||||
Self::sync_server_to_apps(state, server)?;
|
||||
for app in AppType::all() {
|
||||
if matches!(app, AppType::OpenClaw) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for server in servers.values() {
|
||||
if server.apps.is_enabled_for(&app) {
|
||||
Self::sync_server_to_app(state, server, &app)?;
|
||||
} else {
|
||||
Self::remove_server_from_app(state, &server.id, &app)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
+150
-44
@@ -1,6 +1,7 @@
|
||||
use crate::config::write_json_file;
|
||||
use crate::config::{atomic_write, write_json_file};
|
||||
use crate::error::AppError;
|
||||
use crate::opencode_config::get_opencode_dir;
|
||||
use crate::provider::Provider;
|
||||
use crate::store::AppState;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Map, Value};
|
||||
@@ -21,33 +22,41 @@ type OmoProfileData = (Option<Value>, Option<Value>, Option<Value>);
|
||||
// ── Variant descriptor ─────────────────────────────────────────
|
||||
|
||||
pub struct OmoVariant {
|
||||
pub filename: &'static str,
|
||||
pub preferred_filename: &'static str,
|
||||
pub config_candidates: &'static [&'static str],
|
||||
pub category: &'static str,
|
||||
pub provider_prefix: &'static str,
|
||||
pub plugin_name: &'static str,
|
||||
pub plugin_prefix: &'static str,
|
||||
pub plugin_prefixes: &'static [&'static str],
|
||||
pub has_categories: bool,
|
||||
pub label: &'static str,
|
||||
pub import_label: &'static str,
|
||||
}
|
||||
|
||||
pub const STANDARD: OmoVariant = OmoVariant {
|
||||
filename: "oh-my-opencode.jsonc",
|
||||
preferred_filename: "oh-my-openagent.jsonc",
|
||||
config_candidates: &[
|
||||
"oh-my-openagent.jsonc",
|
||||
"oh-my-openagent.json",
|
||||
"oh-my-opencode.jsonc",
|
||||
"oh-my-opencode.json",
|
||||
],
|
||||
category: "omo",
|
||||
provider_prefix: "omo-",
|
||||
plugin_name: "oh-my-opencode@latest",
|
||||
plugin_prefix: "oh-my-opencode",
|
||||
plugin_name: "oh-my-openagent@latest",
|
||||
plugin_prefixes: &["oh-my-openagent", "oh-my-opencode"],
|
||||
has_categories: true,
|
||||
label: "OMO",
|
||||
import_label: "Imported",
|
||||
};
|
||||
|
||||
pub const SLIM: OmoVariant = OmoVariant {
|
||||
filename: "oh-my-opencode-slim.jsonc",
|
||||
preferred_filename: "oh-my-opencode-slim.jsonc",
|
||||
config_candidates: &["oh-my-opencode-slim.jsonc", "oh-my-opencode-slim.json"],
|
||||
category: "omo-slim",
|
||||
provider_prefix: "omo-slim-",
|
||||
plugin_name: "oh-my-opencode-slim@latest",
|
||||
plugin_prefix: "oh-my-opencode-slim",
|
||||
plugin_prefixes: &["oh-my-opencode-slim"],
|
||||
has_categories: false,
|
||||
label: "OMO Slim",
|
||||
import_label: "Imported Slim",
|
||||
@@ -60,22 +69,27 @@ pub struct OmoService;
|
||||
impl OmoService {
|
||||
// ── Path helpers ────────────────────────────────────────
|
||||
|
||||
fn config_candidates(v: &OmoVariant, base_dir: &Path) -> Vec<PathBuf> {
|
||||
v.config_candidates
|
||||
.iter()
|
||||
.map(|name| base_dir.join(name))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn find_existing_config_path(v: &OmoVariant, base_dir: &Path) -> Option<PathBuf> {
|
||||
Self::config_candidates(v, base_dir)
|
||||
.into_iter()
|
||||
.find(|path| path.exists())
|
||||
}
|
||||
|
||||
fn config_path(v: &OmoVariant) -> PathBuf {
|
||||
get_opencode_dir().join(v.filename)
|
||||
let base_dir = get_opencode_dir();
|
||||
Self::find_existing_config_path(v, &base_dir)
|
||||
.unwrap_or_else(|| base_dir.join(v.preferred_filename))
|
||||
}
|
||||
|
||||
fn resolve_local_config_path(v: &OmoVariant) -> Result<PathBuf, AppError> {
|
||||
let config_path = Self::config_path(v);
|
||||
if config_path.exists() {
|
||||
return Ok(config_path);
|
||||
}
|
||||
|
||||
let json_path = config_path.with_extension("json");
|
||||
if json_path.exists() {
|
||||
return Ok(json_path);
|
||||
}
|
||||
|
||||
Err(AppError::OmoConfigNotFound)
|
||||
Self::find_existing_config_path(v, &get_opencode_dir()).ok_or(AppError::OmoConfigNotFound)
|
||||
}
|
||||
|
||||
fn read_jsonc_object(path: &Path) -> Result<Map<String, Value>, AppError> {
|
||||
@@ -120,44 +134,102 @@ impl OmoService {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Public API (variant-parameterized) ─────────────────
|
||||
|
||||
pub fn delete_config_file(v: &OmoVariant) -> Result<(), AppError> {
|
||||
let config_path = Self::config_path(v);
|
||||
if config_path.exists() {
|
||||
std::fs::remove_file(&config_path).map_err(|e| AppError::io(&config_path, e))?;
|
||||
log::info!("{} config file deleted: {config_path:?}", v.label);
|
||||
}
|
||||
crate::opencode_config::remove_plugin_by_prefix(v.plugin_prefix)?;
|
||||
Ok(())
|
||||
fn profile_data_from_provider(provider: &Provider, v: &OmoVariant) -> OmoProfileData {
|
||||
let agents = provider.settings_config.get("agents").cloned();
|
||||
let categories = if v.has_categories {
|
||||
provider.settings_config.get("categories").cloned()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let other_fields = provider.settings_config.get("otherFields").cloned();
|
||||
(agents, categories, other_fields)
|
||||
}
|
||||
|
||||
pub fn write_config_to_file(state: &AppState, v: &OmoVariant) -> Result<(), AppError> {
|
||||
let current_omo = state.db.get_current_omo_provider("opencode", v.category)?;
|
||||
let profile_data = current_omo.as_ref().map(|p| {
|
||||
let agents = p.settings_config.get("agents").cloned();
|
||||
let categories = if v.has_categories {
|
||||
p.settings_config.get("categories").cloned()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let other_fields = p.settings_config.get("otherFields").cloned();
|
||||
(agents, categories, other_fields)
|
||||
});
|
||||
fn snapshot_config_file(path: &Path) -> Result<Option<Vec<u8>>, AppError> {
|
||||
if !path.exists() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let merged = Self::build_config(v, profile_data.as_ref());
|
||||
std::fs::read(path)
|
||||
.map(Some)
|
||||
.map_err(|e| AppError::io(path, e))
|
||||
}
|
||||
|
||||
fn restore_config_file(path: &Path, snapshot: Option<&[u8]>) -> Result<(), AppError> {
|
||||
match snapshot {
|
||||
Some(bytes) => atomic_write(path, bytes),
|
||||
None => {
|
||||
if path.exists() {
|
||||
std::fs::remove_file(path).map_err(|e| AppError::io(path, e))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn write_profile_config(
|
||||
v: &OmoVariant,
|
||||
profile_data: Option<&OmoProfileData>,
|
||||
) -> Result<(), AppError> {
|
||||
let merged = Self::build_config(v, profile_data);
|
||||
let config_path = Self::config_path(v);
|
||||
|
||||
if let Some(parent) = config_path.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| AppError::io(parent, e))?;
|
||||
}
|
||||
|
||||
let previous_contents = Self::snapshot_config_file(&config_path)?;
|
||||
write_json_file(&config_path, &merged)?;
|
||||
crate::opencode_config::add_plugin(v.plugin_name)?;
|
||||
if let Err(err) = crate::opencode_config::add_plugin(v.plugin_name) {
|
||||
if let Err(rollback_err) =
|
||||
Self::restore_config_file(&config_path, previous_contents.as_deref())
|
||||
{
|
||||
log::warn!(
|
||||
"Failed to roll back {} config after plugin sync error: {}",
|
||||
v.label,
|
||||
rollback_err
|
||||
);
|
||||
}
|
||||
return Err(err);
|
||||
}
|
||||
log::info!("{} config written to {config_path:?}", v.label);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ── Public API (variant-parameterized) ─────────────────
|
||||
|
||||
pub fn delete_config_file(v: &OmoVariant) -> Result<(), AppError> {
|
||||
let base_dir = get_opencode_dir();
|
||||
let mut deleted_paths = Vec::new();
|
||||
for config_path in Self::config_candidates(v, &base_dir) {
|
||||
if config_path.exists() {
|
||||
std::fs::remove_file(&config_path).map_err(|e| AppError::io(&config_path, e))?;
|
||||
deleted_paths.push(config_path);
|
||||
}
|
||||
}
|
||||
if !deleted_paths.is_empty() {
|
||||
log::info!("{} config files deleted: {deleted_paths:?}", v.label);
|
||||
}
|
||||
crate::opencode_config::remove_plugins_by_prefixes(v.plugin_prefixes)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn write_config_to_file(state: &AppState, v: &OmoVariant) -> Result<(), AppError> {
|
||||
let current_omo = state.db.get_current_omo_provider("opencode", v.category)?;
|
||||
let profile_data = current_omo
|
||||
.as_ref()
|
||||
.map(|provider| Self::profile_data_from_provider(provider, v));
|
||||
Self::write_profile_config(v, profile_data.as_ref())
|
||||
}
|
||||
|
||||
pub fn write_provider_config_to_file(
|
||||
provider: &Provider,
|
||||
v: &OmoVariant,
|
||||
) -> Result<(), AppError> {
|
||||
let profile_data = Self::profile_data_from_provider(provider, v);
|
||||
Self::write_profile_config(v, Some(&profile_data))
|
||||
}
|
||||
|
||||
fn build_config(v: &OmoVariant, profile_data: Option<&OmoProfileData>) -> Value {
|
||||
let mut result = Map::new();
|
||||
if let Some((agents, categories, other_fields)) = profile_data {
|
||||
@@ -451,4 +523,38 @@ mod tests {
|
||||
assert!(obj.contains_key("agents"));
|
||||
assert!(obj.contains_key("disabled_agents"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_find_existing_config_prefers_new_name_over_old() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let old_path = dir.path().join("oh-my-opencode.jsonc");
|
||||
let new_path = dir.path().join("oh-my-openagent.jsonc");
|
||||
|
||||
// Create both old and new files
|
||||
std::fs::write(&old_path, r#"{"agents":{}}"#).unwrap();
|
||||
std::fs::write(&new_path, r#"{"agents":{}}"#).unwrap();
|
||||
|
||||
let found = OmoService::find_existing_config_path(&STANDARD, dir.path());
|
||||
assert_eq!(
|
||||
found.unwrap(),
|
||||
new_path,
|
||||
"When both old and new config files exist, the new name (oh-my-openagent) must be preferred"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_find_existing_config_falls_back_to_old_name() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let old_path = dir.path().join("oh-my-opencode.jsonc");
|
||||
|
||||
// Only old file exists
|
||||
std::fs::write(&old_path, r#"{"agents":{}}"#).unwrap();
|
||||
|
||||
let found = OmoService::find_existing_config_path(&STANDARD, dir.path());
|
||||
assert_eq!(
|
||||
found.unwrap(),
|
||||
old_path,
|
||||
"When only the old config file exists, it should still be found"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,6 +33,19 @@ pub(crate) fn sanitize_claude_settings_for_live(settings: &Value) -> Value {
|
||||
v
|
||||
}
|
||||
|
||||
pub(crate) fn provider_exists_in_live_config(
|
||||
app_type: &AppType,
|
||||
provider_id: &str,
|
||||
) -> Result<bool, AppError> {
|
||||
match app_type {
|
||||
AppType::OpenCode => crate::opencode_config::get_providers()
|
||||
.map(|providers| providers.contains_key(provider_id)),
|
||||
AppType::OpenClaw => crate::openclaw_config::get_providers()
|
||||
.map(|providers| providers.contains_key(provider_id)),
|
||||
_ => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
fn json_is_subset(target: &Value, source: &Value) -> bool {
|
||||
match source {
|
||||
Value::Object(source_map) => {
|
||||
@@ -461,19 +474,18 @@ fn apply_common_config_to_settings(
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn write_live_with_common_config(
|
||||
pub(crate) fn build_effective_settings_with_common_config(
|
||||
db: &Database,
|
||||
app_type: &AppType,
|
||||
provider: &Provider,
|
||||
) -> Result<(), AppError> {
|
||||
) -> Result<Value, AppError> {
|
||||
let snippet = db.get_config_snippet(app_type.as_str())?;
|
||||
let mut effective_provider = provider.clone();
|
||||
let mut effective_settings = provider.settings_config.clone();
|
||||
|
||||
if provider_uses_common_config(app_type, provider, snippet.as_deref()) {
|
||||
if let Some(snippet_text) = snippet.as_deref() {
|
||||
match apply_common_config_to_settings(app_type, &provider.settings_config, snippet_text)
|
||||
{
|
||||
Ok(settings) => effective_provider.settings_config = settings,
|
||||
match apply_common_config_to_settings(app_type, &effective_settings, snippet_text) {
|
||||
Ok(settings) => effective_settings = settings,
|
||||
Err(err) => {
|
||||
log::warn!(
|
||||
"Failed to apply common config for {} provider '{}': {err}",
|
||||
@@ -485,6 +497,18 @@ pub(crate) fn write_live_with_common_config(
|
||||
}
|
||||
}
|
||||
|
||||
Ok(effective_settings)
|
||||
}
|
||||
|
||||
pub(crate) fn write_live_with_common_config(
|
||||
db: &Database,
|
||||
app_type: &AppType,
|
||||
provider: &Provider,
|
||||
) -> Result<(), AppError> {
|
||||
let mut effective_provider = provider.clone();
|
||||
effective_provider.settings_config =
|
||||
build_effective_settings_with_common_config(db, app_type, provider)?;
|
||||
|
||||
write_live_snapshot(app_type, &effective_provider)
|
||||
}
|
||||
|
||||
@@ -716,10 +740,10 @@ pub(crate) fn write_live_snapshot(app_type: &AppType, provider: &Provider) -> Re
|
||||
provider.id
|
||||
);
|
||||
} else {
|
||||
log::error!(
|
||||
"OpenCode provider '{}' has invalid config structure, skipping write",
|
||||
return Err(AppError::Message(format!(
|
||||
"OpenCode provider '{}' has invalid config structure for live config (must contain 'npm' or 'options')",
|
||||
provider.id
|
||||
);
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -758,10 +782,10 @@ pub(crate) fn write_live_snapshot(app_type: &AppType, provider: &Provider) -> Re
|
||||
provider.id
|
||||
);
|
||||
} else {
|
||||
log::error!(
|
||||
"OpenClaw provider '{}' has invalid config structure, skipping write",
|
||||
return Err(AppError::Message(format!(
|
||||
"OpenClaw provider '{}' has invalid config structure for live config (must contain 'baseUrl', 'api', or 'models')",
|
||||
provider.id
|
||||
);
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -776,23 +800,30 @@ pub(crate) fn write_live_snapshot(app_type: &AppType, provider: &Provider) -> Re
|
||||
/// Used for OpenCode and other additive mode applications.
|
||||
fn sync_all_providers_to_live(state: &AppState, app_type: &AppType) -> Result<(), AppError> {
|
||||
let providers = state.db.get_all_providers(app_type.as_str())?;
|
||||
let mut synced_count = 0usize;
|
||||
|
||||
for provider in providers.values() {
|
||||
if provider
|
||||
.meta
|
||||
.as_ref()
|
||||
.and_then(|meta| meta.live_config_managed)
|
||||
== Some(false)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Err(e) = write_live_with_common_config(state.db.as_ref(), app_type, provider) {
|
||||
log::warn!(
|
||||
"Failed to sync {:?} provider '{}' to live: {e}",
|
||||
app_type,
|
||||
provider.id
|
||||
);
|
||||
// Continue syncing other providers, don't abort
|
||||
continue;
|
||||
}
|
||||
synced_count += 1;
|
||||
}
|
||||
|
||||
log::info!(
|
||||
"Synced {} {:?} providers to live config",
|
||||
providers.len(),
|
||||
app_type
|
||||
);
|
||||
log::info!("Synced {synced_count} {app_type:?} providers to live config");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1196,12 +1227,16 @@ pub fn import_opencode_providers_from_live(state: &AppState) -> Result<usize, Ap
|
||||
};
|
||||
|
||||
// Create provider
|
||||
let provider = Provider::with_id(
|
||||
let mut provider = Provider::with_id(
|
||||
id.clone(),
|
||||
config.name.clone().unwrap_or_else(|| id.clone()),
|
||||
settings_config,
|
||||
None,
|
||||
);
|
||||
provider.meta = Some(crate::provider::ProviderMeta {
|
||||
live_config_managed: Some(true),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
// Save to database
|
||||
if let Err(e) = state.db.save_provider("opencode", &provider) {
|
||||
@@ -1266,7 +1301,11 @@ pub fn import_openclaw_providers_from_live(state: &AppState) -> Result<usize, Ap
|
||||
.unwrap_or_else(|| id.clone());
|
||||
|
||||
// Create provider
|
||||
let provider = Provider::with_id(id.clone(), display_name, settings_config, None);
|
||||
let mut provider = Provider::with_id(id.clone(), display_name, settings_config, None);
|
||||
provider.meta = Some(crate::provider::ProviderMeta {
|
||||
live_config_managed: Some(true),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
// Save to database
|
||||
if let Err(e) = state.db.save_provider("openclaw", &provider) {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+670
-147
@@ -7,8 +7,11 @@ use crate::config::{get_claude_settings_path, read_json_file, write_json_file};
|
||||
use crate::database::Database;
|
||||
use crate::provider::Provider;
|
||||
use crate::proxy::server::ProxyServer;
|
||||
use crate::proxy::switch_lock::SwitchLockManager;
|
||||
use crate::proxy::types::*;
|
||||
use crate::services::provider::write_live_with_common_config;
|
||||
use crate::services::provider::{
|
||||
build_effective_settings_with_common_config, write_live_with_common_config,
|
||||
};
|
||||
use serde_json::{json, Value};
|
||||
use std::str::FromStr;
|
||||
use std::sync::Arc;
|
||||
@@ -17,7 +20,7 @@ use tokio::sync::RwLock;
|
||||
/// 用于接管 Live 配置时的占位符(避免客户端提示缺少 key,同时不泄露真实 Token)
|
||||
const PROXY_TOKEN_PLACEHOLDER: &str = "PROXY_MANAGED";
|
||||
|
||||
/// 代理接管模式下需要从 Claude Live 配置中移除的“模型覆盖”字段。
|
||||
/// 代理接管模式下需要从 Claude Live 配置中移除的"模型覆盖"字段。
|
||||
///
|
||||
/// 原因:接管模式切换供应商时不会写回 Live 配置,如果保留这些字段,
|
||||
/// Claude Code 会继续以旧模型名发起请求,导致新供应商不支持时失败。
|
||||
@@ -37,6 +40,12 @@ pub struct ProxyService {
|
||||
server: Arc<RwLock<Option<ProxyServer>>>,
|
||||
/// AppHandle,用于传递给 ProxyServer 以支持故障转移时的 UI 更新
|
||||
app_handle: Arc<RwLock<Option<tauri::AppHandle>>>,
|
||||
switch_locks: SwitchLockManager,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct HotSwitchOutcome {
|
||||
pub logical_target_changed: bool,
|
||||
}
|
||||
|
||||
impl ProxyService {
|
||||
@@ -45,12 +54,13 @@ impl ProxyService {
|
||||
db,
|
||||
server: Arc::new(RwLock::new(None)),
|
||||
app_handle: Arc::new(RwLock::new(None)),
|
||||
switch_locks: SwitchLockManager::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 清理接管模式下 Claude Live 配置中的模型覆盖字段。
|
||||
///
|
||||
/// 这可以避免“接管开启后切换供应商仍使用旧模型”的问题。
|
||||
/// 这可以避免"接管开启后切换供应商仍使用旧模型"的问题。
|
||||
/// 注意:此方法不会修改 Token/Base URL 的接管占位符,仅移除模型字段。
|
||||
pub fn cleanup_claude_model_overrides_in_live(&self) -> Result<(), String> {
|
||||
let mut config = self.read_claude_live()?;
|
||||
@@ -1098,6 +1108,11 @@ impl ProxyService {
|
||||
|
||||
/// 恢复指定应用的 Live 配置(若无备份则不做任何操作)
|
||||
async fn restore_live_config_for_app(&self, app_type: &AppType) -> Result<(), String> {
|
||||
let _guard = self.switch_locks.lock_for_app(app_type.as_str()).await;
|
||||
self.restore_live_config_for_app_inner(app_type).await
|
||||
}
|
||||
|
||||
async fn restore_live_config_for_app_inner(&self, app_type: &AppType) -> Result<(), String> {
|
||||
match app_type {
|
||||
AppType::Claude => {
|
||||
if let Ok(Some(backup)) = self.db.get_live_backup("claude").await {
|
||||
@@ -1157,10 +1172,19 @@ impl ProxyService {
|
||||
async fn restore_live_config_for_app_with_fallback(
|
||||
&self,
|
||||
app_type: &AppType,
|
||||
) -> Result<(), String> {
|
||||
let _guard = self.switch_locks.lock_for_app(app_type.as_str()).await;
|
||||
self.restore_live_config_for_app_with_fallback_inner(app_type)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn restore_live_config_for_app_with_fallback_inner(
|
||||
&self,
|
||||
app_type: &AppType,
|
||||
) -> Result<(), String> {
|
||||
let app_type_str = app_type.as_str();
|
||||
|
||||
// 1) 优先从 Live 备份恢复(这是“原始 Live”的唯一可靠来源)
|
||||
// 1) 优先从 Live 备份恢复(这是"原始 Live"的唯一可靠来源)
|
||||
let backup = self
|
||||
.db
|
||||
.get_live_backup(app_type_str)
|
||||
@@ -1179,7 +1203,7 @@ impl ProxyService {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// 2.1) 优先从 SSOT(当前供应商)重建 Live(比“清理字段”更可用)
|
||||
// 2.1) 优先从 SSOT(当前供应商)重建 Live(比"清理字段"更可用)
|
||||
match self.restore_live_from_ssot_for_app(app_type) {
|
||||
Ok(true) => {
|
||||
log::info!("{app_type_str} Live 配置已从 SSOT 恢复(无备份兜底)");
|
||||
@@ -1356,51 +1380,9 @@ impl ProxyService {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remove local proxy base_url from TOML(委托给 codex_config 共享实现)
|
||||
fn remove_local_toml_base_url(toml_str: &str) -> String {
|
||||
use toml_edit::DocumentMut;
|
||||
|
||||
let mut doc = match toml_str.parse::<DocumentMut>() {
|
||||
Ok(doc) => doc,
|
||||
Err(_) => return toml_str.to_string(),
|
||||
};
|
||||
|
||||
let model_provider = doc
|
||||
.get("model_provider")
|
||||
.and_then(|item| item.as_str())
|
||||
.map(str::to_string);
|
||||
|
||||
if let Some(provider_key) = model_provider {
|
||||
if let Some(model_providers) = doc
|
||||
.get_mut("model_providers")
|
||||
.and_then(|v| v.as_table_mut())
|
||||
{
|
||||
if let Some(provider_table) = model_providers
|
||||
.get_mut(provider_key.as_str())
|
||||
.and_then(|v| v.as_table_mut())
|
||||
{
|
||||
let should_remove = provider_table
|
||||
.get("base_url")
|
||||
.and_then(|item| item.as_str())
|
||||
.map(Self::is_local_proxy_url)
|
||||
.unwrap_or(false);
|
||||
if should_remove {
|
||||
provider_table.remove("base_url");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 兜底:清理顶层 base_url(仅当它看起来像本地代理地址)
|
||||
let should_remove_root = doc
|
||||
.get("base_url")
|
||||
.and_then(|item| item.as_str())
|
||||
.map(Self::is_local_proxy_url)
|
||||
.unwrap_or(false);
|
||||
if should_remove_root {
|
||||
doc.as_table_mut().remove("base_url");
|
||||
}
|
||||
|
||||
doc.to_string()
|
||||
crate::codex_config::remove_codex_toml_base_url_if(toml_str, Self::is_local_proxy_url)
|
||||
}
|
||||
|
||||
fn cleanup_gemini_takeover_placeholders_in_live(&self) -> Result<(), String> {
|
||||
@@ -1457,7 +1439,7 @@ impl ProxyService {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 检测 Live 配置是否处于“被接管”的残留状态
|
||||
/// 检测 Live 配置是否处于"被接管"的残留状态
|
||||
///
|
||||
/// 用于兜底处理:当数据库备份缺失但 Live 文件已经写成代理占位符时,
|
||||
/// 启动流程可以据此触发恢复逻辑。
|
||||
@@ -1528,21 +1510,48 @@ impl ProxyService {
|
||||
app_type: &str,
|
||||
provider: &Provider,
|
||||
) -> Result<(), String> {
|
||||
let backup_json = match app_type {
|
||||
"claude" => {
|
||||
// Claude: settings_config 直接作为备份
|
||||
serde_json::to_string(&provider.settings_config)
|
||||
.map_err(|e| format!("序列化 Claude 配置失败: {e}"))?
|
||||
let _guard = self.switch_locks.lock_for_app(app_type).await;
|
||||
self.update_live_backup_from_provider_inner(app_type, provider)
|
||||
.await
|
||||
}
|
||||
|
||||
/// 仅供已持有 per-app 切换锁的调用方使用。
|
||||
async fn update_live_backup_from_provider_inner(
|
||||
&self,
|
||||
app_type: &str,
|
||||
provider: &Provider,
|
||||
) -> Result<(), String> {
|
||||
let app_type_enum =
|
||||
AppType::from_str(app_type).map_err(|_| format!("未知的应用类型: {app_type}"))?;
|
||||
let mut effective_settings =
|
||||
build_effective_settings_with_common_config(self.db.as_ref(), &app_type_enum, provider)
|
||||
.map_err(|e| format!("构建 {app_type} 有效配置失败: {e}"))?;
|
||||
|
||||
if matches!(app_type_enum, AppType::Codex) {
|
||||
let existing_backup = self
|
||||
.db
|
||||
.get_live_backup(app_type)
|
||||
.await
|
||||
.map_err(|e| format!("读取 {app_type} 现有备份失败: {e}"))?;
|
||||
|
||||
if let Some(existing_backup) = existing_backup {
|
||||
let existing_value: Value = serde_json::from_str(&existing_backup.original_config)
|
||||
.map_err(|e| format!("解析 {app_type} 现有备份失败: {e}"))?;
|
||||
Self::preserve_codex_mcp_servers_in_backup(
|
||||
&mut effective_settings,
|
||||
&existing_value,
|
||||
)?;
|
||||
}
|
||||
"codex" => {
|
||||
// Codex: settings_config 包含 {"auth": ..., "config": ...},直接使用
|
||||
serde_json::to_string(&provider.settings_config)
|
||||
.map_err(|e| format!("序列化 Codex 配置失败: {e}"))?
|
||||
}
|
||||
"gemini" => {
|
||||
// Gemini: 只提取 env 字段(与原始备份格式一致)
|
||||
// proxy.rs 的 read_gemini_live() 返回 {"env": {...}}
|
||||
let env_backup = if let Some(env) = provider.settings_config.get("env") {
|
||||
}
|
||||
|
||||
let backup_json = match app_type_enum {
|
||||
AppType::Claude => serde_json::to_string(&effective_settings)
|
||||
.map_err(|e| format!("序列化 Claude 配置失败: {e}"))?,
|
||||
AppType::Codex => serde_json::to_string(&effective_settings)
|
||||
.map_err(|e| format!("序列化 Codex 配置失败: {e}"))?,
|
||||
AppType::Gemini => {
|
||||
// Gemini takeover 仅修改 .env;settings.json(含 mcpServers)保持原样。
|
||||
let env_backup = if let Some(env) = effective_settings.get("env") {
|
||||
json!({ "env": env })
|
||||
} else {
|
||||
json!({ "env": {} })
|
||||
@@ -1550,7 +1559,9 @@ impl ProxyService {
|
||||
serde_json::to_string(&env_backup)
|
||||
.map_err(|e| format!("序列化 Gemini 配置失败: {e}"))?
|
||||
}
|
||||
_ => return Err(format!("未知的应用类型: {app_type}")),
|
||||
AppType::OpenCode | AppType::OpenClaw => {
|
||||
return Err(format!("未知的应用类型: {app_type}"));
|
||||
}
|
||||
};
|
||||
|
||||
self.db
|
||||
@@ -1562,101 +1573,152 @@ impl ProxyService {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn hot_switch_provider(
|
||||
&self,
|
||||
app_type: &str,
|
||||
provider_id: &str,
|
||||
) -> Result<HotSwitchOutcome, String> {
|
||||
let _guard = self.switch_locks.lock_for_app(app_type).await;
|
||||
|
||||
let app_type_enum =
|
||||
AppType::from_str(app_type).map_err(|_| format!("无效的应用类型: {app_type}"))?;
|
||||
let provider = self
|
||||
.db
|
||||
.get_provider_by_id(provider_id, app_type)
|
||||
.map_err(|e| format!("读取供应商失败: {e}"))?
|
||||
.ok_or_else(|| format!("供应商不存在: {provider_id}"))?;
|
||||
|
||||
let logical_target_changed =
|
||||
crate::settings::get_effective_current_provider(&self.db, &app_type_enum)
|
||||
.map_err(|e| format!("读取当前供应商失败: {e}"))?
|
||||
.as_deref()
|
||||
!= Some(provider_id);
|
||||
|
||||
let has_backup = self
|
||||
.db
|
||||
.get_live_backup(app_type_enum.as_str())
|
||||
.await
|
||||
.map_err(|e| format!("读取 {app_type} 备份失败: {e}"))?
|
||||
.is_some();
|
||||
let live_taken_over = self.detect_takeover_in_live_config_for_app(&app_type_enum);
|
||||
let should_sync_backup = has_backup || live_taken_over;
|
||||
|
||||
self.db
|
||||
.set_current_provider(app_type_enum.as_str(), provider_id)
|
||||
.map_err(|e| format!("更新当前供应商失败: {e}"))?;
|
||||
crate::settings::set_current_provider(&app_type_enum, Some(provider_id))
|
||||
.map_err(|e| format!("更新本地当前供应商失败: {e}"))?;
|
||||
|
||||
if should_sync_backup {
|
||||
self.update_live_backup_from_provider_inner(app_type, &provider)
|
||||
.await?;
|
||||
|
||||
if matches!(app_type_enum, AppType::Claude) {
|
||||
if let Err(e) = self.cleanup_claude_model_overrides_in_live() {
|
||||
log::warn!("清理 Claude Live 模型字段失败(不影响热切换结果): {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(server) = self.server.read().await.as_ref() {
|
||||
server
|
||||
.set_active_target(app_type_enum.as_str(), &provider.id, &provider.name)
|
||||
.await;
|
||||
}
|
||||
|
||||
Ok(HotSwitchOutcome {
|
||||
logical_target_changed,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
async fn lock_switch_for_test(&self, app_type: &str) -> tokio::sync::OwnedMutexGuard<()> {
|
||||
self.switch_locks.lock_for_app(app_type).await
|
||||
}
|
||||
|
||||
fn preserve_codex_mcp_servers_in_backup(
|
||||
target_settings: &mut Value,
|
||||
existing_backup: &Value,
|
||||
) -> Result<(), String> {
|
||||
let target_obj = target_settings
|
||||
.as_object_mut()
|
||||
.ok_or_else(|| "Codex 备份必须是 JSON 对象".to_string())?;
|
||||
|
||||
let target_config = target_obj
|
||||
.get("config")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
let mut target_doc = if target_config.trim().is_empty() {
|
||||
toml_edit::DocumentMut::new()
|
||||
} else {
|
||||
target_config
|
||||
.parse::<toml_edit::DocumentMut>()
|
||||
.map_err(|e| format!("解析新的 Codex config.toml 失败: {e}"))?
|
||||
};
|
||||
|
||||
let existing_config = existing_backup
|
||||
.get("config")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
if existing_config.trim().is_empty() {
|
||||
target_obj.insert("config".to_string(), json!(target_doc.to_string()));
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let existing_doc = existing_config
|
||||
.parse::<toml_edit::DocumentMut>()
|
||||
.map_err(|e| format!("解析现有 Codex 备份失败: {e}"))?;
|
||||
|
||||
if let Some(existing_mcp_servers) = existing_doc.get("mcp_servers") {
|
||||
match target_doc.get_mut("mcp_servers") {
|
||||
Some(target_mcp_servers) => {
|
||||
if let (Some(target_table), Some(existing_table)) = (
|
||||
target_mcp_servers.as_table_like_mut(),
|
||||
existing_mcp_servers.as_table_like(),
|
||||
) {
|
||||
for (server_id, server_item) in existing_table.iter() {
|
||||
if target_table.get(server_id).is_none() {
|
||||
target_table.insert(server_id, server_item.clone());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
log::warn!(
|
||||
"Codex config contains a non-table mcp_servers section; skipping backup MCP merge"
|
||||
);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
target_doc["mcp_servers"] = existing_mcp_servers.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
target_obj.insert("config".to_string(), json!(target_doc.to_string()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 代理模式下切换供应商(热切换,不写 Live)
|
||||
pub async fn switch_proxy_target(
|
||||
&self,
|
||||
app_type: &str,
|
||||
provider_id: &str,
|
||||
) -> Result<(), String> {
|
||||
// 代理模式切换供应商(热切换):
|
||||
// - 更新 SSOT(数据库 is_current)
|
||||
// - 同步本地 settings(设备级 current_provider_*)
|
||||
// - 若该应用正处于接管模式,则同步更新 Live 备份(用于停止代理时恢复)
|
||||
let app_type_enum =
|
||||
AppType::from_str(app_type).map_err(|_| format!("无效的应用类型: {app_type}"))?;
|
||||
let outcome = self.hot_switch_provider(app_type, provider_id).await?;
|
||||
|
||||
self.db
|
||||
.set_current_provider(app_type_enum.as_str(), provider_id)
|
||||
.map_err(|e| format!("更新当前供应商失败: {e}"))?;
|
||||
|
||||
// 同步本地 settings(设备级优先)
|
||||
crate::settings::set_current_provider(&app_type_enum, Some(provider_id))
|
||||
.map_err(|e| format!("更新本地当前供应商失败: {e}"))?;
|
||||
|
||||
// 仅在确实处于接管状态时才更新 Live 备份,避免无接管时误写覆盖 Live
|
||||
let has_backup = self
|
||||
.db
|
||||
.get_live_backup(app_type_enum.as_str())
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
.is_some();
|
||||
let live_taken_over = self.detect_takeover_in_live_config_for_app(&app_type_enum);
|
||||
|
||||
if let Ok(Some(provider)) = self.db.get_provider_by_id(provider_id, app_type) {
|
||||
// 同步更新 Live 备份(用于 stop_with_restore 恢复)
|
||||
if has_backup || live_taken_over {
|
||||
self.update_live_backup_from_provider(app_type, &provider)
|
||||
.await?;
|
||||
}
|
||||
|
||||
// 同步更新 ProxyStatus.active_targets(用于 UI 立即反映切换目标)
|
||||
if let Some(server) = self.server.read().await.as_ref() {
|
||||
server
|
||||
.set_active_target(app_type_enum.as_str(), &provider.id, &provider.name)
|
||||
.await;
|
||||
}
|
||||
if outcome.logical_target_changed {
|
||||
log::info!("代理模式:已切换 {app_type} 的目标供应商为 {provider_id}");
|
||||
} else {
|
||||
log::debug!("代理模式:{app_type} 已对齐到目标供应商 {provider_id}");
|
||||
}
|
||||
|
||||
log::info!("代理模式:已切换 {app_type} 的目标供应商为 {provider_id}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ==================== Live 配置读写辅助方法 ====================
|
||||
|
||||
/// 更新 TOML 字符串中的 base_url
|
||||
/// 更新 TOML 字符串中的 base_url(委托给 codex_config 共享实现)
|
||||
fn update_toml_base_url(toml_str: &str, new_url: &str) -> String {
|
||||
use toml_edit::DocumentMut;
|
||||
|
||||
let mut doc = match toml_str.parse::<DocumentMut>() {
|
||||
Ok(doc) => doc,
|
||||
Err(_) => return toml_str.to_string(),
|
||||
};
|
||||
|
||||
// Codex 的 config.toml 通常是:
|
||||
// model_provider = "any"
|
||||
//
|
||||
// [model_providers.any]
|
||||
// base_url = "https://.../v1"
|
||||
//
|
||||
// 所以接管时要“精准”修改当前 model_provider 对应的 model_providers.<name>.base_url,
|
||||
// 避免写错位置导致 Codex 仍然走旧地址。
|
||||
let model_provider = doc
|
||||
.get("model_provider")
|
||||
.and_then(|item| item.as_str())
|
||||
.map(str::to_string);
|
||||
|
||||
if let Some(provider_key) = model_provider {
|
||||
if doc.get("model_providers").is_none() {
|
||||
doc["model_providers"] = toml_edit::table();
|
||||
}
|
||||
|
||||
if let Some(model_providers) = doc["model_providers"].as_table_mut() {
|
||||
if !model_providers.contains_key(&provider_key) {
|
||||
model_providers[&provider_key] = toml_edit::table();
|
||||
}
|
||||
|
||||
if let Some(provider_table) = model_providers[&provider_key].as_table_mut() {
|
||||
provider_table["base_url"] = toml_edit::value(new_url);
|
||||
return doc.to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 兜底:如果没有 model_provider 或结构不符合预期,则退回修改顶层 base_url。
|
||||
doc["base_url"] = toml_edit::value(new_url);
|
||||
|
||||
doc.to_string()
|
||||
crate::codex_config::update_codex_toml_field(toml_str, "base_url", new_url)
|
||||
.unwrap_or_else(|_| toml_str.to_string())
|
||||
}
|
||||
|
||||
fn read_claude_live(&self) -> Result<Value, String> {
|
||||
@@ -1914,6 +1976,7 @@ impl ProxyService {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::provider::ProviderMeta;
|
||||
use serial_test::serial;
|
||||
use std::env;
|
||||
use tempfile::TempDir;
|
||||
@@ -2166,7 +2229,7 @@ model = "gpt-5.1-codex"
|
||||
db.set_current_provider("claude", "a")
|
||||
.expect("set current provider");
|
||||
|
||||
// 模拟“已接管”状态:存在 Live 备份(内容不重要,会被热切换更新)
|
||||
// 模拟"已接管"状态:存在 Live 备份(内容不重要,会被热切换更新)
|
||||
db.save_live_backup("claude", "{\"env\":{}}")
|
||||
.await
|
||||
.expect("seed live backup");
|
||||
@@ -2191,4 +2254,464 @@ model = "gpt-5.1-codex"
|
||||
let expected = serde_json::to_string(&provider_b.settings_config).expect("serialize");
|
||||
assert_eq!(backup.original_config, expected);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn hot_switch_provider_serializes_same_app_switches() {
|
||||
use tokio::time::{sleep, Duration};
|
||||
|
||||
let _home = TempHome::new();
|
||||
crate::settings::reload_settings().expect("reload settings");
|
||||
|
||||
let db = Arc::new(Database::memory().expect("init db"));
|
||||
let service = ProxyService::new(db.clone());
|
||||
|
||||
let provider_a = Provider::with_id(
|
||||
"a".to_string(),
|
||||
"A".to_string(),
|
||||
json!({ "env": { "ANTHROPIC_API_KEY": "a-key" } }),
|
||||
None,
|
||||
);
|
||||
let provider_b = Provider::with_id(
|
||||
"b".to_string(),
|
||||
"B".to_string(),
|
||||
json!({ "env": { "ANTHROPIC_API_KEY": "b-key" } }),
|
||||
None,
|
||||
);
|
||||
let provider_c = Provider::with_id(
|
||||
"c".to_string(),
|
||||
"C".to_string(),
|
||||
json!({ "env": { "ANTHROPIC_API_KEY": "c-key" } }),
|
||||
None,
|
||||
);
|
||||
|
||||
db.save_provider("claude", &provider_a)
|
||||
.expect("save provider a");
|
||||
db.save_provider("claude", &provider_b)
|
||||
.expect("save provider b");
|
||||
db.save_provider("claude", &provider_c)
|
||||
.expect("save provider c");
|
||||
db.set_current_provider("claude", "a")
|
||||
.expect("set current provider");
|
||||
crate::settings::set_current_provider(&AppType::Claude, Some("a"))
|
||||
.expect("set local current provider");
|
||||
db.save_live_backup("claude", "{\"env\":{}}")
|
||||
.await
|
||||
.expect("seed live backup");
|
||||
|
||||
let guard = service.lock_switch_for_test("claude").await;
|
||||
let service_for_b = service.clone();
|
||||
let service_for_c = service.clone();
|
||||
|
||||
let switch_b = tokio::spawn(async move {
|
||||
service_for_b
|
||||
.hot_switch_provider("claude", "b")
|
||||
.await
|
||||
.expect("switch to b")
|
||||
});
|
||||
sleep(Duration::from_millis(20)).await;
|
||||
let switch_c = tokio::spawn(async move {
|
||||
service_for_c
|
||||
.hot_switch_provider("claude", "c")
|
||||
.await
|
||||
.expect("switch to c")
|
||||
});
|
||||
|
||||
sleep(Duration::from_millis(20)).await;
|
||||
drop(guard);
|
||||
|
||||
let outcome_b = switch_b.await.expect("join switch b");
|
||||
let outcome_c = switch_c.await.expect("join switch c");
|
||||
assert!(outcome_b.logical_target_changed);
|
||||
assert!(outcome_c.logical_target_changed);
|
||||
|
||||
assert_eq!(
|
||||
crate::settings::get_effective_current_provider(&db, &AppType::Claude)
|
||||
.expect("effective current"),
|
||||
Some("c".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
crate::settings::get_current_provider(&AppType::Claude).as_deref(),
|
||||
Some("c")
|
||||
);
|
||||
assert_eq!(
|
||||
db.get_current_provider("claude").expect("db current"),
|
||||
Some("c".to_string())
|
||||
);
|
||||
|
||||
let backup = db
|
||||
.get_live_backup("claude")
|
||||
.await
|
||||
.expect("get live backup")
|
||||
.expect("backup exists");
|
||||
let expected = serde_json::to_string(&provider_c.settings_config).expect("serialize");
|
||||
assert_eq!(backup.original_config, expected);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn restore_waits_for_hot_switch_and_restores_latest_backup() {
|
||||
use tokio::time::{sleep, Duration};
|
||||
|
||||
let _home = TempHome::new();
|
||||
crate::settings::reload_settings().expect("reload settings");
|
||||
|
||||
let db = Arc::new(Database::memory().expect("init db"));
|
||||
let service = ProxyService::new(db.clone());
|
||||
|
||||
let provider_a = Provider::with_id(
|
||||
"a".to_string(),
|
||||
"A".to_string(),
|
||||
json!({ "env": { "ANTHROPIC_API_KEY": "a-key" } }),
|
||||
None,
|
||||
);
|
||||
let provider_b = Provider::with_id(
|
||||
"b".to_string(),
|
||||
"B".to_string(),
|
||||
json!({ "env": { "ANTHROPIC_API_KEY": "b-key" } }),
|
||||
None,
|
||||
);
|
||||
|
||||
db.save_provider("claude", &provider_a)
|
||||
.expect("save provider a");
|
||||
db.save_provider("claude", &provider_b)
|
||||
.expect("save provider b");
|
||||
db.set_current_provider("claude", "a")
|
||||
.expect("set current provider");
|
||||
crate::settings::set_current_provider(&AppType::Claude, Some("a"))
|
||||
.expect("set local current provider");
|
||||
db.save_live_backup(
|
||||
"claude",
|
||||
&serde_json::to_string(&provider_a.settings_config).expect("serialize provider a"),
|
||||
)
|
||||
.await
|
||||
.expect("seed live backup");
|
||||
service
|
||||
.write_claude_live(&json!({ "env": { "ANTHROPIC_API_KEY": "stale" } }))
|
||||
.expect("seed live file");
|
||||
|
||||
let guard = service.lock_switch_for_test("claude").await;
|
||||
let service_for_switch = service.clone();
|
||||
let service_for_restore = service.clone();
|
||||
|
||||
let switch_to_b = tokio::spawn(async move {
|
||||
service_for_switch
|
||||
.hot_switch_provider("claude", "b")
|
||||
.await
|
||||
.expect("switch to b")
|
||||
});
|
||||
sleep(Duration::from_millis(20)).await;
|
||||
let restore = tokio::spawn(async move {
|
||||
service_for_restore
|
||||
.restore_live_config_for_app_with_fallback(&AppType::Claude)
|
||||
.await
|
||||
.expect("restore claude live")
|
||||
});
|
||||
|
||||
sleep(Duration::from_millis(20)).await;
|
||||
drop(guard);
|
||||
|
||||
let outcome = switch_to_b.await.expect("join switch");
|
||||
restore.await.expect("join restore");
|
||||
assert!(outcome.logical_target_changed);
|
||||
|
||||
assert_eq!(
|
||||
crate::settings::get_effective_current_provider(&db, &AppType::Claude)
|
||||
.expect("effective current"),
|
||||
Some("b".to_string())
|
||||
);
|
||||
|
||||
let backup = db
|
||||
.get_live_backup("claude")
|
||||
.await
|
||||
.expect("get live backup")
|
||||
.expect("backup exists");
|
||||
let expected = serde_json::to_string(&provider_b.settings_config).expect("serialize");
|
||||
assert_eq!(backup.original_config, expected);
|
||||
assert_eq!(
|
||||
service.read_claude_live().expect("read live"),
|
||||
provider_b.settings_config
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn update_live_backup_from_provider_applies_claude_common_config() {
|
||||
let _home = TempHome::new();
|
||||
crate::settings::reload_settings().expect("reload settings");
|
||||
|
||||
let db = Arc::new(Database::memory().expect("init db"));
|
||||
db.set_config_snippet(
|
||||
"claude",
|
||||
Some(
|
||||
serde_json::json!({
|
||||
"includeCoAuthoredBy": false
|
||||
})
|
||||
.to_string(),
|
||||
),
|
||||
)
|
||||
.expect("set common config snippet");
|
||||
|
||||
let service = ProxyService::new(db.clone());
|
||||
|
||||
let mut provider = Provider::with_id(
|
||||
"p1".to_string(),
|
||||
"P1".to_string(),
|
||||
json!({
|
||||
"env": {
|
||||
"ANTHROPIC_AUTH_TOKEN": "token",
|
||||
"ANTHROPIC_BASE_URL": "https://claude.example"
|
||||
}
|
||||
}),
|
||||
None,
|
||||
);
|
||||
provider.meta = Some(ProviderMeta {
|
||||
common_config_enabled: Some(true),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
service
|
||||
.update_live_backup_from_provider("claude", &provider)
|
||||
.await
|
||||
.expect("update live backup");
|
||||
|
||||
let backup = db
|
||||
.get_live_backup("claude")
|
||||
.await
|
||||
.expect("get live backup")
|
||||
.expect("backup exists");
|
||||
let stored: Value =
|
||||
serde_json::from_str(&backup.original_config).expect("parse backup json");
|
||||
|
||||
assert_eq!(
|
||||
stored.get("includeCoAuthoredBy").and_then(|v| v.as_bool()),
|
||||
Some(false),
|
||||
"common config should be applied into Claude restore backup"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn update_live_backup_from_provider_applies_codex_common_config() {
|
||||
let _home = TempHome::new();
|
||||
crate::settings::reload_settings().expect("reload settings");
|
||||
|
||||
let db = Arc::new(Database::memory().expect("init db"));
|
||||
db.set_config_snippet(
|
||||
"codex",
|
||||
Some("disable_response_storage = true\n".to_string()),
|
||||
)
|
||||
.expect("set common config snippet");
|
||||
|
||||
let service = ProxyService::new(db.clone());
|
||||
|
||||
let mut provider = Provider::with_id(
|
||||
"p1".to_string(),
|
||||
"P1".to_string(),
|
||||
json!({
|
||||
"auth": {
|
||||
"OPENAI_API_KEY": "token"
|
||||
},
|
||||
"config": r#"model_provider = "any"
|
||||
model = "gpt-5"
|
||||
|
||||
[model_providers.any]
|
||||
base_url = "https://codex.example/v1"
|
||||
"#
|
||||
}),
|
||||
None,
|
||||
);
|
||||
provider.meta = Some(ProviderMeta {
|
||||
common_config_enabled: Some(true),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
service
|
||||
.update_live_backup_from_provider("codex", &provider)
|
||||
.await
|
||||
.expect("update live backup");
|
||||
|
||||
let backup = db
|
||||
.get_live_backup("codex")
|
||||
.await
|
||||
.expect("get live backup")
|
||||
.expect("backup exists");
|
||||
let stored: Value =
|
||||
serde_json::from_str(&backup.original_config).expect("parse backup json");
|
||||
let config = stored
|
||||
.get("config")
|
||||
.and_then(|v| v.as_str())
|
||||
.expect("config string");
|
||||
|
||||
assert!(
|
||||
config.contains("disable_response_storage = true"),
|
||||
"common config should be applied into Codex restore backup"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn update_live_backup_from_provider_preserves_codex_mcp_servers() {
|
||||
let _home = TempHome::new();
|
||||
crate::settings::reload_settings().expect("reload settings");
|
||||
|
||||
let db = Arc::new(Database::memory().expect("init db"));
|
||||
let service = ProxyService::new(db.clone());
|
||||
|
||||
db.save_live_backup(
|
||||
"codex",
|
||||
&serde_json::to_string(&json!({
|
||||
"auth": {
|
||||
"OPENAI_API_KEY": "old-token"
|
||||
},
|
||||
"config": r#"model_provider = "any"
|
||||
model = "gpt-4"
|
||||
|
||||
[model_providers.any]
|
||||
base_url = "https://old.example/v1"
|
||||
|
||||
[mcp_servers.echo]
|
||||
command = "npx"
|
||||
args = ["echo-server"]
|
||||
"#
|
||||
}))
|
||||
.expect("serialize seed backup"),
|
||||
)
|
||||
.await
|
||||
.expect("seed live backup");
|
||||
|
||||
let provider = Provider::with_id(
|
||||
"p2".to_string(),
|
||||
"P2".to_string(),
|
||||
json!({
|
||||
"auth": {
|
||||
"OPENAI_API_KEY": "new-token"
|
||||
},
|
||||
"config": r#"model_provider = "any"
|
||||
model = "gpt-5"
|
||||
|
||||
[model_providers.any]
|
||||
base_url = "https://new.example/v1"
|
||||
"#
|
||||
}),
|
||||
None,
|
||||
);
|
||||
|
||||
service
|
||||
.update_live_backup_from_provider("codex", &provider)
|
||||
.await
|
||||
.expect("update live backup");
|
||||
|
||||
let backup = db
|
||||
.get_live_backup("codex")
|
||||
.await
|
||||
.expect("get live backup")
|
||||
.expect("backup exists");
|
||||
let stored: Value =
|
||||
serde_json::from_str(&backup.original_config).expect("parse backup json");
|
||||
let config = stored
|
||||
.get("config")
|
||||
.and_then(|v| v.as_str())
|
||||
.expect("config string");
|
||||
|
||||
assert!(
|
||||
config.contains("[mcp_servers.echo]"),
|
||||
"existing Codex MCP section should survive proxy hot-switch backup update"
|
||||
);
|
||||
assert!(
|
||||
config.contains("https://new.example/v1"),
|
||||
"provider-specific base_url should still update to the new provider"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn update_live_backup_from_provider_keeps_new_codex_mcp_entries_on_conflict() {
|
||||
let _home = TempHome::new();
|
||||
crate::settings::reload_settings().expect("reload settings");
|
||||
|
||||
let db = Arc::new(Database::memory().expect("init db"));
|
||||
let service = ProxyService::new(db.clone());
|
||||
|
||||
db.save_live_backup(
|
||||
"codex",
|
||||
&serde_json::to_string(&json!({
|
||||
"auth": {
|
||||
"OPENAI_API_KEY": "old-token"
|
||||
},
|
||||
"config": r#"[mcp_servers.shared]
|
||||
command = "old-command"
|
||||
|
||||
[mcp_servers.legacy]
|
||||
command = "legacy-command"
|
||||
"#
|
||||
}))
|
||||
.expect("serialize seed backup"),
|
||||
)
|
||||
.await
|
||||
.expect("seed live backup");
|
||||
|
||||
let provider = Provider::with_id(
|
||||
"p2".to_string(),
|
||||
"P2".to_string(),
|
||||
json!({
|
||||
"auth": {
|
||||
"OPENAI_API_KEY": "new-token"
|
||||
},
|
||||
"config": r#"[mcp_servers.shared]
|
||||
command = "new-command"
|
||||
|
||||
[mcp_servers.latest]
|
||||
command = "latest-command"
|
||||
"#
|
||||
}),
|
||||
None,
|
||||
);
|
||||
|
||||
service
|
||||
.update_live_backup_from_provider("codex", &provider)
|
||||
.await
|
||||
.expect("update live backup");
|
||||
|
||||
let backup = db
|
||||
.get_live_backup("codex")
|
||||
.await
|
||||
.expect("get live backup")
|
||||
.expect("backup exists");
|
||||
let stored: Value =
|
||||
serde_json::from_str(&backup.original_config).expect("parse backup json");
|
||||
let config = stored
|
||||
.get("config")
|
||||
.and_then(|v| v.as_str())
|
||||
.expect("config string");
|
||||
let parsed: toml::Value = toml::from_str(config).expect("parse merged codex config");
|
||||
|
||||
let mcp_servers = parsed
|
||||
.get("mcp_servers")
|
||||
.expect("mcp_servers should be present");
|
||||
assert_eq!(
|
||||
mcp_servers
|
||||
.get("shared")
|
||||
.and_then(|v| v.get("command"))
|
||||
.and_then(|v| v.as_str()),
|
||||
Some("new-command"),
|
||||
"new provider/common-config MCP definition should win on conflict"
|
||||
);
|
||||
assert_eq!(
|
||||
mcp_servers
|
||||
.get("legacy")
|
||||
.and_then(|v| v.get("command"))
|
||||
.and_then(|v| v.as_str()),
|
||||
Some("legacy-command"),
|
||||
"backup-only MCP entries should still be preserved"
|
||||
);
|
||||
assert_eq!(
|
||||
mcp_servers
|
||||
.get("latest")
|
||||
.and_then(|v| v.get("command"))
|
||||
.and_then(|v| v.as_str()),
|
||||
Some("latest-command"),
|
||||
"new MCP entries should remain in the restore backup"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+435
-13
@@ -152,6 +152,33 @@ impl Default for SkillStore {
|
||||
}
|
||||
}
|
||||
|
||||
/// Skill 卸载结果
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SkillUninstallResult {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub backup_path: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SkillBackupEntry {
|
||||
pub backup_id: String,
|
||||
pub backup_path: String,
|
||||
pub created_at: i64,
|
||||
pub skill: InstalledSkill,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct SkillBackupMetadata {
|
||||
skill: InstalledSkill,
|
||||
backup_created_at: i64,
|
||||
source_path: String,
|
||||
}
|
||||
|
||||
const SKILL_BACKUP_RETAIN_COUNT: usize = 20;
|
||||
|
||||
/// 技能元数据 (从 SKILL.md 解析)
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct SkillMetadata {
|
||||
@@ -159,6 +186,21 @@ pub struct SkillMetadata {
|
||||
pub description: Option<String>,
|
||||
}
|
||||
|
||||
/// 导入已有 Skill 时,前端显式提交的启用应用选择
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ImportSkillSelection {
|
||||
pub directory: String,
|
||||
#[serde(default)]
|
||||
pub apps: SkillApps,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
struct LegacySkillMigrationRow {
|
||||
directory: String,
|
||||
app_type: String,
|
||||
}
|
||||
|
||||
// ========== ~/.agents/ lock 文件解析 ==========
|
||||
|
||||
/// `~/.agents/.skill-lock.json` 文件结构
|
||||
@@ -354,6 +396,13 @@ impl SkillService {
|
||||
Ok(dir)
|
||||
}
|
||||
|
||||
/// 获取 Skill 卸载备份目录(~/.cc-switch/skill-backups/)
|
||||
fn get_backup_dir() -> Result<PathBuf> {
|
||||
let dir = get_app_config_dir().join("skill-backups");
|
||||
fs::create_dir_all(&dir)?;
|
||||
Ok(dir)
|
||||
}
|
||||
|
||||
/// 获取应用的 skills 目录
|
||||
pub fn get_app_skills_dir(app: &AppType) -> Result<PathBuf> {
|
||||
// 目录覆盖:优先使用用户在 settings.json 中配置的 override 目录
|
||||
@@ -621,12 +670,15 @@ impl SkillService {
|
||||
/// 1. 从所有应用目录删除
|
||||
/// 2. 从 SSOT 删除
|
||||
/// 3. 从数据库删除
|
||||
pub fn uninstall(db: &Arc<Database>, id: &str) -> Result<()> {
|
||||
pub fn uninstall(db: &Arc<Database>, id: &str) -> Result<SkillUninstallResult> {
|
||||
// 获取 skill 信息
|
||||
let skill = db
|
||||
.get_installed_skill(id)?
|
||||
.ok_or_else(|| anyhow!("Skill not found: {id}"))?;
|
||||
|
||||
let backup_path =
|
||||
Self::create_uninstall_backup(&skill)?.map(|path| path.to_string_lossy().to_string());
|
||||
|
||||
// 从所有应用目录删除
|
||||
for app in AppType::all() {
|
||||
let _ = Self::remove_from_app(&skill.directory, &app);
|
||||
@@ -642,11 +694,137 @@ impl SkillService {
|
||||
// 从数据库删除
|
||||
db.delete_skill(id)?;
|
||||
|
||||
log::info!("Skill {} 卸载成功", skill.name);
|
||||
log::info!(
|
||||
"Skill {} 卸载成功{}",
|
||||
skill.name,
|
||||
backup_path
|
||||
.as_deref()
|
||||
.map(|path| format!(", backup: {path}"))
|
||||
.unwrap_or_default()
|
||||
);
|
||||
|
||||
Ok(SkillUninstallResult { backup_path })
|
||||
}
|
||||
|
||||
pub fn list_backups() -> Result<Vec<SkillBackupEntry>> {
|
||||
let backup_dir = Self::get_backup_dir()?;
|
||||
let mut entries = Vec::new();
|
||||
|
||||
for entry in fs::read_dir(&backup_dir)? {
|
||||
let entry = match entry {
|
||||
Ok(entry) => entry,
|
||||
Err(err) => {
|
||||
log::warn!("读取 Skill 备份目录项失败: {err}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let path = entry.path();
|
||||
if !path.is_dir() {
|
||||
continue;
|
||||
}
|
||||
|
||||
match Self::read_backup_metadata(&path) {
|
||||
Ok(metadata) => entries.push(SkillBackupEntry {
|
||||
backup_id: entry.file_name().to_string_lossy().to_string(),
|
||||
backup_path: path.to_string_lossy().to_string(),
|
||||
created_at: metadata.backup_created_at,
|
||||
skill: metadata.skill,
|
||||
}),
|
||||
Err(err) => {
|
||||
log::warn!("解析 Skill 备份失败 {}: {err:#}", path.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
entries.sort_by(|a, b| b.created_at.cmp(&a.created_at));
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
pub fn delete_backup(backup_id: &str) -> Result<()> {
|
||||
let backup_path = Self::backup_path_for_id(backup_id)?;
|
||||
let metadata = fs::symlink_metadata(&backup_path)
|
||||
.with_context(|| format!("failed to access {}", backup_path.display()))?;
|
||||
|
||||
if !metadata.is_dir() {
|
||||
return Err(anyhow!(
|
||||
"Skill backup is not a directory: {}",
|
||||
backup_path.display()
|
||||
));
|
||||
}
|
||||
|
||||
fs::remove_dir_all(&backup_path)
|
||||
.with_context(|| format!("failed to delete {}", backup_path.display()))?;
|
||||
|
||||
log::info!("Skill 备份已删除: {}", backup_path.display());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn restore_from_backup(
|
||||
db: &Arc<Database>,
|
||||
backup_id: &str,
|
||||
current_app: &AppType,
|
||||
) -> Result<InstalledSkill> {
|
||||
let backup_path = Self::backup_path_for_id(backup_id)?;
|
||||
let metadata = Self::read_backup_metadata(&backup_path)?;
|
||||
let backup_skill_dir = backup_path.join("skill");
|
||||
if !backup_skill_dir.join("SKILL.md").exists() {
|
||||
return Err(anyhow!(
|
||||
"Skill backup is invalid or missing SKILL.md: {}",
|
||||
backup_path.display()
|
||||
));
|
||||
}
|
||||
|
||||
let existing_skills = db.get_all_installed_skills()?;
|
||||
if existing_skills.contains_key(&metadata.skill.id)
|
||||
|| existing_skills.values().any(|skill| {
|
||||
skill
|
||||
.directory
|
||||
.eq_ignore_ascii_case(&metadata.skill.directory)
|
||||
})
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"Skill already exists, please uninstall the current one first: {}",
|
||||
metadata.skill.directory
|
||||
));
|
||||
}
|
||||
|
||||
let ssot_dir = Self::get_ssot_dir()?;
|
||||
let restore_path = ssot_dir.join(&metadata.skill.directory);
|
||||
if restore_path.exists() || Self::is_symlink(&restore_path) {
|
||||
return Err(anyhow!(
|
||||
"Restore target already exists: {}",
|
||||
restore_path.display()
|
||||
));
|
||||
}
|
||||
|
||||
let mut restored_skill = metadata.skill;
|
||||
restored_skill.installed_at = Utc::now().timestamp();
|
||||
restored_skill.apps = SkillApps::only(current_app);
|
||||
|
||||
Self::copy_dir_recursive(&backup_skill_dir, &restore_path)?;
|
||||
|
||||
if let Err(err) = db.save_skill(&restored_skill) {
|
||||
let _ = fs::remove_dir_all(&restore_path);
|
||||
return Err(err.into());
|
||||
}
|
||||
|
||||
if !restored_skill.apps.is_empty() {
|
||||
if let Err(err) = Self::sync_to_app_dir(&restored_skill.directory, current_app) {
|
||||
let _ = db.delete_skill(&restored_skill.id);
|
||||
let _ = fs::remove_dir_all(&restore_path);
|
||||
return Err(err);
|
||||
}
|
||||
}
|
||||
|
||||
log::info!(
|
||||
"Skill {} 已从备份恢复到 {}",
|
||||
restored_skill.name,
|
||||
restore_path.display()
|
||||
);
|
||||
|
||||
Ok(restored_skill)
|
||||
}
|
||||
|
||||
/// 切换应用启用状态
|
||||
///
|
||||
/// 启用:复制到应用目录
|
||||
@@ -717,6 +895,9 @@ impl SkillService {
|
||||
}
|
||||
|
||||
let skill_md = path.join("SKILL.md");
|
||||
if !skill_md.exists() {
|
||||
continue;
|
||||
}
|
||||
let (name, description) = Self::read_skill_name_desc(&skill_md, &dir_name);
|
||||
|
||||
unmanaged
|
||||
@@ -740,14 +921,18 @@ impl SkillService {
|
||||
/// 将未管理的 Skills 导入到 CC Switch 统一管理
|
||||
pub fn import_from_apps(
|
||||
db: &Arc<Database>,
|
||||
directories: Vec<String>,
|
||||
imports: Vec<ImportSkillSelection>,
|
||||
) -> Result<Vec<InstalledSkill>> {
|
||||
let ssot_dir = Self::get_ssot_dir()?;
|
||||
let agents_lock = parse_agents_lock();
|
||||
let mut imported = Vec::new();
|
||||
|
||||
// 将 lock 文件中发现的仓库保存到 skill_repos
|
||||
save_repos_from_lock(db, &agents_lock, directories.iter().map(|s| s.as_str()));
|
||||
save_repos_from_lock(
|
||||
db,
|
||||
&agents_lock,
|
||||
imports.iter().map(|selection| selection.directory.as_str()),
|
||||
);
|
||||
|
||||
// 收集所有候选搜索目录
|
||||
let mut search_sources: Vec<(PathBuf, String)> = Vec::new();
|
||||
@@ -761,10 +946,10 @@ impl SkillService {
|
||||
}
|
||||
search_sources.push((ssot_dir.clone(), "cc-switch".to_string()));
|
||||
|
||||
for dir_name in directories {
|
||||
for selection in imports {
|
||||
let dir_name = selection.directory;
|
||||
// 在所有候选目录中查找
|
||||
let mut source_path: Option<PathBuf> = None;
|
||||
let mut found_in: Vec<String> = Vec::new();
|
||||
|
||||
for (base, label) in &search_sources {
|
||||
let skill_path = base.join(&dir_name);
|
||||
@@ -772,7 +957,7 @@ impl SkillService {
|
||||
if source_path.is_none() {
|
||||
source_path = Some(skill_path);
|
||||
}
|
||||
found_in.push(label.clone());
|
||||
log::debug!("Skill '{dir_name}' found in source '{label}'");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -780,6 +965,14 @@ impl SkillService {
|
||||
Some(p) => p,
|
||||
None => continue,
|
||||
};
|
||||
if !source.join("SKILL.md").exists() {
|
||||
log::warn!(
|
||||
"Skip importing '{}' because source '{}' has no SKILL.md",
|
||||
dir_name,
|
||||
source.display()
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// 复制到 SSOT
|
||||
let dest = ssot_dir.join(&dir_name);
|
||||
@@ -791,8 +984,8 @@ impl SkillService {
|
||||
let skill_md = dest.join("SKILL.md");
|
||||
let (name, description) = Self::read_skill_name_desc(&skill_md, &dir_name);
|
||||
|
||||
// 构建启用状态
|
||||
let apps = SkillApps::from_labels(&found_in);
|
||||
// 启用状态仅信任用户本次显式选择,不再根据“在哪些位置找到”自动推断。
|
||||
let apps = selection.apps;
|
||||
|
||||
// 从 lock 文件提取仓库信息
|
||||
let (id, repo_owner, repo_name, repo_branch, readme_url) =
|
||||
@@ -935,6 +1128,33 @@ impl SkillService {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 判断路径是否为指向 SSOT 目录内的符号链接。
|
||||
fn is_symlink_to_ssot(path: &Path, ssot_dir: &Path) -> bool {
|
||||
if !Self::is_symlink(path) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let Ok(target) = fs::read_link(path) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
if target.is_absolute() && target.starts_with(ssot_dir) {
|
||||
return true;
|
||||
}
|
||||
|
||||
let resolved = path
|
||||
.parent()
|
||||
.map(|parent| parent.join(&target))
|
||||
.unwrap_or(target.clone());
|
||||
|
||||
let canonical_ssot = ssot_dir
|
||||
.canonicalize()
|
||||
.unwrap_or_else(|_| ssot_dir.to_path_buf());
|
||||
let canonical_target = resolved.canonicalize().unwrap_or(resolved);
|
||||
|
||||
canonical_target.starts_with(&canonical_ssot)
|
||||
}
|
||||
|
||||
/// 从应用目录删除 Skill(支持 symlink 和真实目录)
|
||||
pub fn remove_from_app(directory: &str, app: &AppType) -> Result<()> {
|
||||
let app_dir = Self::get_app_skills_dir(app)?;
|
||||
@@ -951,6 +1171,36 @@ impl SkillService {
|
||||
/// 同步所有已启用的 Skills 到指定应用
|
||||
pub fn sync_to_app(db: &Arc<Database>, app: &AppType) -> Result<()> {
|
||||
let skills = db.get_all_installed_skills()?;
|
||||
let ssot_dir = Self::get_ssot_dir()?;
|
||||
let app_dir = Self::get_app_skills_dir(app)?;
|
||||
|
||||
let indexed_skills: HashMap<String, &InstalledSkill> = skills
|
||||
.values()
|
||||
.map(|skill| (skill.directory.to_lowercase(), skill))
|
||||
.collect();
|
||||
|
||||
if app_dir.exists() {
|
||||
for entry in fs::read_dir(&app_dir)? {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
let dir_name = entry.file_name().to_string_lossy().to_string();
|
||||
|
||||
if dir_name.starts_with('.') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(skill) = indexed_skills.get(&dir_name.to_lowercase()) {
|
||||
if !skill.apps.is_enabled_for(app) {
|
||||
Self::remove_path(&path)?;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if Self::is_symlink_to_ssot(&path, &ssot_dir) {
|
||||
Self::remove_path(&path)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for skill in skills.values() {
|
||||
if skill.apps.is_enabled_for(app) {
|
||||
@@ -1413,6 +1663,144 @@ impl SkillService {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn resolve_uninstall_backup_source(skill: &InstalledSkill) -> Result<Option<PathBuf>> {
|
||||
let ssot_path = Self::get_ssot_dir()?.join(&skill.directory);
|
||||
if ssot_path.is_dir() {
|
||||
return Ok(Some(ssot_path));
|
||||
}
|
||||
|
||||
for app in AppType::all() {
|
||||
let app_dir = match Self::get_app_skills_dir(&app) {
|
||||
Ok(dir) => dir,
|
||||
Err(_) => continue,
|
||||
};
|
||||
let candidate = app_dir.join(&skill.directory);
|
||||
if candidate.is_dir() {
|
||||
return Ok(Some(candidate));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn sanitize_backup_segment(segment: &str) -> String {
|
||||
let sanitized = segment
|
||||
.chars()
|
||||
.map(|c| match c {
|
||||
'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' | '.' => c,
|
||||
_ => '-',
|
||||
})
|
||||
.collect::<String>()
|
||||
.trim_matches('-')
|
||||
.to_string();
|
||||
|
||||
if sanitized.is_empty() {
|
||||
"skill".to_string()
|
||||
} else {
|
||||
sanitized
|
||||
}
|
||||
}
|
||||
|
||||
fn cleanup_old_skill_backups(dir: &Path) -> Result<()> {
|
||||
let mut entries = fs::read_dir(dir)?
|
||||
.filter_map(|entry| entry.ok())
|
||||
.filter_map(|entry| {
|
||||
let metadata = entry.metadata().ok()?;
|
||||
if !metadata.is_dir() {
|
||||
return None;
|
||||
}
|
||||
Some((entry.path(), metadata.modified().ok()))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
if entries.len() <= SKILL_BACKUP_RETAIN_COUNT {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
entries.sort_by_key(|(_, modified)| *modified);
|
||||
let remove_count = entries.len().saturating_sub(SKILL_BACKUP_RETAIN_COUNT);
|
||||
|
||||
for (path, _) in entries.into_iter().take(remove_count) {
|
||||
fs::remove_dir_all(&path)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn backup_path_for_id(backup_id: &str) -> Result<PathBuf> {
|
||||
if backup_id.contains("..")
|
||||
|| backup_id.contains('/')
|
||||
|| backup_id.contains('\\')
|
||||
|| backup_id.trim().is_empty()
|
||||
{
|
||||
return Err(anyhow!("Invalid backup id: {backup_id}"));
|
||||
}
|
||||
|
||||
Ok(Self::get_backup_dir()?.join(backup_id))
|
||||
}
|
||||
|
||||
fn read_backup_metadata(backup_path: &Path) -> Result<SkillBackupMetadata> {
|
||||
let metadata_path = backup_path.join("meta.json");
|
||||
let content = fs::read_to_string(&metadata_path)
|
||||
.with_context(|| format!("failed to read {}", metadata_path.display()))?;
|
||||
serde_json::from_str(&content)
|
||||
.with_context(|| format!("failed to parse {}", metadata_path.display()))
|
||||
}
|
||||
|
||||
fn create_uninstall_backup(skill: &InstalledSkill) -> Result<Option<PathBuf>> {
|
||||
let Some(source_path) = Self::resolve_uninstall_backup_source(skill)? else {
|
||||
log::warn!(
|
||||
"Skill {} 卸载前未找到可备份的目录,将跳过备份",
|
||||
skill.directory
|
||||
);
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let backup_root = Self::get_backup_dir()?;
|
||||
let timestamp = Utc::now().format("%Y%m%d_%H%M%S");
|
||||
let slug = Self::sanitize_backup_segment(&skill.directory);
|
||||
let mut backup_path = backup_root.join(format!("{timestamp}_{slug}"));
|
||||
let mut counter = 1;
|
||||
while backup_path.exists() {
|
||||
backup_path = backup_root.join(format!("{timestamp}_{slug}_{counter}"));
|
||||
counter += 1;
|
||||
}
|
||||
|
||||
let write_backup = || -> Result<()> {
|
||||
let skill_backup_dir = backup_path.join("skill");
|
||||
Self::copy_dir_recursive(&source_path, &skill_backup_dir)?;
|
||||
|
||||
let metadata = SkillBackupMetadata {
|
||||
skill: skill.clone(),
|
||||
backup_created_at: Utc::now().timestamp(),
|
||||
source_path: source_path.to_string_lossy().to_string(),
|
||||
};
|
||||
let metadata_path = backup_path.join("meta.json");
|
||||
let metadata_json = serde_json::to_string_pretty(&metadata)
|
||||
.context("failed to serialize skill backup metadata")?;
|
||||
fs::write(&metadata_path, metadata_json)
|
||||
.with_context(|| format!("failed to write {}", metadata_path.display()))?;
|
||||
Ok(())
|
||||
};
|
||||
|
||||
if let Err(err) = write_backup() {
|
||||
let _ = fs::remove_dir_all(&backup_path);
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
if let Err(err) = Self::cleanup_old_skill_backups(&backup_root) {
|
||||
log::warn!("清理旧 Skill 备份失败: {err:#}");
|
||||
}
|
||||
|
||||
log::info!(
|
||||
"Skill {} 已在卸载前备份到 {}",
|
||||
skill.name,
|
||||
backup_path.display()
|
||||
);
|
||||
|
||||
Ok(Some(backup_path))
|
||||
}
|
||||
|
||||
/// 解析 ZIP 中的符号链接:将目标内容复制到 symlink 位置
|
||||
///
|
||||
/// GitHub ZIP 归档保留了 symlink 元数据,解压时可通过 `is_symlink()` 检测。
|
||||
@@ -1814,8 +2202,32 @@ fn save_repos_from_lock(
|
||||
pub fn migrate_skills_to_ssot(db: &Arc<Database>) -> Result<usize> {
|
||||
let ssot_dir = SkillService::get_ssot_dir()?;
|
||||
let agents_lock = parse_agents_lock();
|
||||
let snapshot: Vec<LegacySkillMigrationRow> =
|
||||
match db.get_setting("skills_ssot_migration_snapshot")? {
|
||||
Some(value) if !value.trim().is_empty() => match serde_json::from_str(&value) {
|
||||
Ok(rows) => rows,
|
||||
Err(err) => {
|
||||
log::warn!("解析 skills 迁移快照失败,将回退到文件系统扫描: {err}");
|
||||
Vec::new()
|
||||
}
|
||||
},
|
||||
_ => Vec::new(),
|
||||
};
|
||||
|
||||
let has_snapshot = !snapshot.is_empty();
|
||||
let mut discovered: HashMap<String, SkillApps> = HashMap::new();
|
||||
|
||||
if has_snapshot {
|
||||
for row in &snapshot {
|
||||
if let Ok(app) = row.app_type.parse::<AppType>() {
|
||||
discovered
|
||||
.entry(row.directory.clone())
|
||||
.or_default()
|
||||
.set_enabled_for(&app, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 扫描各应用目录
|
||||
for app in AppType::all() {
|
||||
let app_dir = match SkillService::get_app_skills_dir(&app) {
|
||||
@@ -1838,6 +2250,12 @@ pub fn migrate_skills_to_ssot(db: &Arc<Database>) -> Result<usize> {
|
||||
if dir_name.starts_with('.') {
|
||||
continue;
|
||||
}
|
||||
if !path.join("SKILL.md").exists() {
|
||||
continue;
|
||||
}
|
||||
if has_snapshot && !discovered.contains_key(&dir_name) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 复制到 SSOT(如果不存在)
|
||||
let ssot_path = ssot_dir.join(&dir_name);
|
||||
@@ -1845,10 +2263,12 @@ pub fn migrate_skills_to_ssot(db: &Arc<Database>) -> Result<usize> {
|
||||
SkillService::copy_dir_recursive(&path, &ssot_path)?;
|
||||
}
|
||||
|
||||
discovered
|
||||
.entry(dir_name)
|
||||
.or_default()
|
||||
.set_enabled_for(&app, true);
|
||||
if !has_snapshot {
|
||||
discovered
|
||||
.entry(dir_name)
|
||||
.or_default()
|
||||
.set_enabled_for(&app, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1885,6 +2305,8 @@ pub fn migrate_skills_to_ssot(db: &Arc<Database>) -> Result<usize> {
|
||||
count += 1;
|
||||
}
|
||||
|
||||
let _ = db.set_setting("skills_ssot_migration_snapshot", "");
|
||||
|
||||
log::info!("Skills 迁移完成,共 {count} 个");
|
||||
|
||||
Ok(count)
|
||||
|
||||
@@ -12,6 +12,9 @@ use std::time::Instant;
|
||||
use crate::app_config::AppType;
|
||||
use crate::error::AppError;
|
||||
use crate::provider::Provider;
|
||||
use crate::proxy::providers::copilot_auth;
|
||||
use crate::proxy::providers::transform::anthropic_to_openai;
|
||||
use crate::proxy::providers::transform_responses::anthropic_to_responses;
|
||||
use crate::proxy::providers::{get_adapter, AuthInfo, AuthStrategy};
|
||||
|
||||
/// 健康状态枚举
|
||||
@@ -84,13 +87,22 @@ impl StreamCheckService {
|
||||
app_type: &AppType,
|
||||
provider: &Provider,
|
||||
config: &StreamCheckConfig,
|
||||
auth_override: Option<AuthInfo>,
|
||||
claude_api_format_override: Option<String>,
|
||||
) -> Result<StreamCheckResult, AppError> {
|
||||
// 合并供应商单独配置和全局配置
|
||||
let effective_config = Self::merge_provider_config(provider, config);
|
||||
let mut last_result = None;
|
||||
|
||||
for attempt in 0..=effective_config.max_retries {
|
||||
let result = Self::check_once(app_type, provider, &effective_config).await;
|
||||
let result = Self::check_once(
|
||||
app_type,
|
||||
provider,
|
||||
&effective_config,
|
||||
auth_override.clone(),
|
||||
claude_api_format_override.clone(),
|
||||
)
|
||||
.await;
|
||||
|
||||
match &result {
|
||||
Ok(r) if r.success => {
|
||||
@@ -178,6 +190,8 @@ impl StreamCheckService {
|
||||
app_type: &AppType,
|
||||
provider: &Provider,
|
||||
config: &StreamCheckConfig,
|
||||
auth_override: Option<AuthInfo>,
|
||||
claude_api_format_override: Option<String>,
|
||||
) -> Result<StreamCheckResult, AppError> {
|
||||
let start = Instant::now();
|
||||
let adapter = get_adapter(app_type);
|
||||
@@ -186,8 +200,8 @@ impl StreamCheckService {
|
||||
.extract_base_url(provider)
|
||||
.map_err(|e| AppError::Message(format!("Failed to extract base_url: {e}")))?;
|
||||
|
||||
let auth = adapter
|
||||
.extract_auth(provider)
|
||||
let auth = auth_override
|
||||
.or_else(|| adapter.extract_auth(provider))
|
||||
.ok_or_else(|| AppError::Message("API Key not found".to_string()))?;
|
||||
|
||||
// 获取 HTTP 客户端:优先使用供应商单独代理配置,否则使用全局客户端
|
||||
@@ -208,6 +222,7 @@ impl StreamCheckService {
|
||||
test_prompt,
|
||||
request_timeout,
|
||||
provider,
|
||||
claude_api_format_override.as_deref(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -219,6 +234,7 @@ impl StreamCheckService {
|
||||
&model_to_test,
|
||||
test_prompt,
|
||||
request_timeout,
|
||||
provider,
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -287,6 +303,7 @@ impl StreamCheckService {
|
||||
/// 根据供应商的 api_format 选择请求格式:
|
||||
/// - "anthropic" (默认): Anthropic Messages API (/v1/messages)
|
||||
/// - "openai_chat": OpenAI Chat Completions API (/v1/chat/completions)
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn check_claude_stream(
|
||||
client: &Client,
|
||||
base_url: &str,
|
||||
@@ -295,8 +312,10 @@ impl StreamCheckService {
|
||||
test_prompt: &str,
|
||||
timeout: std::time::Duration,
|
||||
provider: &Provider,
|
||||
claude_api_format_override: Option<&str>,
|
||||
) -> Result<(u16, String), AppError> {
|
||||
let base = base_url.trim_end_matches('/');
|
||||
let is_github_copilot = auth.strategy == AuthStrategy::GitHubCopilot;
|
||||
|
||||
// Detect api_format: meta.api_format > settings_config.api_format > default "anthropic"
|
||||
let api_format = provider
|
||||
@@ -311,40 +330,64 @@ impl StreamCheckService {
|
||||
})
|
||||
.unwrap_or("anthropic");
|
||||
|
||||
let is_openai_chat = api_format == "openai_chat";
|
||||
let effective_api_format = claude_api_format_override.unwrap_or(api_format);
|
||||
|
||||
// URL: /v1/chat/completions for openai_chat, /v1/messages?beta=true for anthropic
|
||||
let url = if is_openai_chat {
|
||||
if base.ends_with("/v1") {
|
||||
format!("{base}/chat/completions")
|
||||
} else {
|
||||
format!("{base}/v1/chat/completions")
|
||||
}
|
||||
} else {
|
||||
// ?beta=true is required by some relay services to verify request origin
|
||||
if base.ends_with("/v1") {
|
||||
format!("{base}/messages?beta=true")
|
||||
} else {
|
||||
format!("{base}/v1/messages?beta=true")
|
||||
}
|
||||
};
|
||||
let is_full_url = provider
|
||||
.meta
|
||||
.as_ref()
|
||||
.and_then(|meta| meta.is_full_url)
|
||||
.unwrap_or(false);
|
||||
let is_openai_chat = effective_api_format == "openai_chat";
|
||||
let is_openai_responses = effective_api_format == "openai_responses";
|
||||
let url =
|
||||
Self::resolve_claude_stream_url(base, auth.strategy, effective_api_format, is_full_url);
|
||||
|
||||
// Body: identical structure for minimal test (both APIs accept messages array)
|
||||
let body = json!({
|
||||
let max_tokens = if is_openai_responses { 16 } else { 1 };
|
||||
|
||||
// Build from Anthropic-native shape first, then convert for configured targets.
|
||||
let anthropic_body = json!({
|
||||
"model": model,
|
||||
"max_tokens": 1,
|
||||
"max_tokens": max_tokens,
|
||||
"messages": [{ "role": "user", "content": test_prompt }],
|
||||
"stream": true
|
||||
});
|
||||
let body = if is_openai_responses {
|
||||
anthropic_to_responses(anthropic_body, Some(&provider.id))
|
||||
.map_err(|e| AppError::Message(format!("Failed to build test request: {e}")))?
|
||||
} else if is_openai_chat {
|
||||
anthropic_to_openai(anthropic_body, Some(&provider.id))
|
||||
.map_err(|e| AppError::Message(format!("Failed to build test request: {e}")))?
|
||||
} else {
|
||||
anthropic_body
|
||||
};
|
||||
|
||||
let mut request_builder = client.post(&url);
|
||||
|
||||
if is_openai_chat {
|
||||
// OpenAI-compatible: Bearer auth + standard headers only
|
||||
if is_github_copilot {
|
||||
request_builder = request_builder
|
||||
.header("authorization", format!("Bearer {}", auth.api_key))
|
||||
.header("content-type", "application/json")
|
||||
.header("accept", "application/json");
|
||||
.header("accept", "text/event-stream")
|
||||
.header("accept-encoding", "identity")
|
||||
.header("user-agent", copilot_auth::COPILOT_USER_AGENT)
|
||||
.header("editor-version", copilot_auth::COPILOT_EDITOR_VERSION)
|
||||
.header(
|
||||
"editor-plugin-version",
|
||||
copilot_auth::COPILOT_PLUGIN_VERSION,
|
||||
)
|
||||
.header(
|
||||
"copilot-integration-id",
|
||||
copilot_auth::COPILOT_INTEGRATION_ID,
|
||||
)
|
||||
.header("x-github-api-version", copilot_auth::COPILOT_API_VERSION)
|
||||
.header("openai-intent", "conversation-panel");
|
||||
} else if is_openai_chat || is_openai_responses {
|
||||
// OpenAI-compatible targets: Bearer auth + SSE headers only
|
||||
request_builder = request_builder
|
||||
.header("authorization", format!("Bearer {}", auth.api_key))
|
||||
.header("content-type", "application/json")
|
||||
.header("accept", "text/event-stream")
|
||||
.header("accept-encoding", "identity");
|
||||
} else {
|
||||
// Anthropic native: full Claude CLI headers
|
||||
let os_name = Self::get_os_name();
|
||||
@@ -424,18 +467,14 @@ impl StreamCheckService {
|
||||
model: &str,
|
||||
test_prompt: &str,
|
||||
timeout: std::time::Duration,
|
||||
provider: &Provider,
|
||||
) -> Result<(u16, String), AppError> {
|
||||
let base = base_url.trim_end_matches('/');
|
||||
// Codex CLI 的 base_url 语义:base_url 是 API base(可能已包含 /v1 或其他自定义前缀),
|
||||
// Responses 端点为 `/responses`。
|
||||
//
|
||||
// 兼容:如果 base_url 配成纯 origin(如 https://api.openai.com),则需要补 `/v1`。
|
||||
// 优先尝试 `{base}/responses`,若 404 再回退 `{base}/v1/responses`。
|
||||
let urls = if base.ends_with("/v1") {
|
||||
vec![format!("{base}/responses")]
|
||||
} else {
|
||||
vec![format!("{base}/responses"), format!("{base}/v1/responses")]
|
||||
};
|
||||
let is_full_url = provider
|
||||
.meta
|
||||
.as_ref()
|
||||
.and_then(|meta| meta.is_full_url)
|
||||
.unwrap_or(false);
|
||||
let urls = Self::resolve_codex_stream_urls(base_url, is_full_url);
|
||||
|
||||
// 解析模型名和推理等级 (支持 model@level 或 model#level 格式)
|
||||
let (actual_model, reasoning_effort) = Self::parse_model_with_effort(model);
|
||||
@@ -692,6 +731,65 @@ impl StreamCheckService {
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_claude_stream_url(
|
||||
base_url: &str,
|
||||
auth_strategy: AuthStrategy,
|
||||
api_format: &str,
|
||||
is_full_url: bool,
|
||||
) -> String {
|
||||
if is_full_url {
|
||||
return base_url.to_string();
|
||||
}
|
||||
|
||||
let base = base_url.trim_end_matches('/');
|
||||
let is_github_copilot = auth_strategy == AuthStrategy::GitHubCopilot;
|
||||
|
||||
if is_github_copilot && api_format == "openai_responses" {
|
||||
format!("{base}/v1/responses")
|
||||
} else if is_github_copilot {
|
||||
format!("{base}/chat/completions")
|
||||
} else if api_format == "openai_responses" {
|
||||
if base.ends_with("/v1") {
|
||||
format!("{base}/responses")
|
||||
} else {
|
||||
format!("{base}/v1/responses")
|
||||
}
|
||||
} else if api_format == "openai_chat" {
|
||||
if base.ends_with("/v1") {
|
||||
format!("{base}/chat/completions")
|
||||
} else {
|
||||
format!("{base}/v1/chat/completions")
|
||||
}
|
||||
} else if base.ends_with("/v1") {
|
||||
format!("{base}/messages")
|
||||
} else {
|
||||
format!("{base}/v1/messages")
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_codex_stream_urls(base_url: &str, is_full_url: bool) -> Vec<String> {
|
||||
if is_full_url {
|
||||
return vec![base_url.to_string()];
|
||||
}
|
||||
|
||||
let base = base_url.trim_end_matches('/');
|
||||
|
||||
if base.ends_with("/v1") {
|
||||
vec![format!("{base}/responses")]
|
||||
} else {
|
||||
vec![format!("{base}/responses"), format!("{base}/v1/responses")]
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn resolve_effective_test_model(
|
||||
app_type: &AppType,
|
||||
provider: &Provider,
|
||||
config: &StreamCheckConfig,
|
||||
) -> String {
|
||||
let effective_config = Self::merge_provider_config(provider, config);
|
||||
Self::resolve_test_model(app_type, provider, &effective_config)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -794,4 +892,107 @@ mod tests {
|
||||
assert_eq!(claude_auth, AuthStrategy::ClaudeAuth);
|
||||
assert_eq!(bearer, AuthStrategy::Bearer);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_claude_stream_url_for_full_url_mode() {
|
||||
let url = StreamCheckService::resolve_claude_stream_url(
|
||||
"https://relay.example/v1/chat/completions",
|
||||
AuthStrategy::Bearer,
|
||||
"openai_chat",
|
||||
true,
|
||||
);
|
||||
|
||||
assert_eq!(url, "https://relay.example/v1/chat/completions");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_claude_stream_url_for_github_copilot() {
|
||||
let url = StreamCheckService::resolve_claude_stream_url(
|
||||
"https://api.githubcopilot.com",
|
||||
AuthStrategy::GitHubCopilot,
|
||||
"openai_chat",
|
||||
false,
|
||||
);
|
||||
|
||||
assert_eq!(url, "https://api.githubcopilot.com/chat/completions");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_claude_stream_url_for_github_copilot_responses() {
|
||||
let url = StreamCheckService::resolve_claude_stream_url(
|
||||
"https://api.githubcopilot.com",
|
||||
AuthStrategy::GitHubCopilot,
|
||||
"openai_responses",
|
||||
false,
|
||||
);
|
||||
|
||||
assert_eq!(url, "https://api.githubcopilot.com/v1/responses");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_claude_stream_url_for_openai_chat() {
|
||||
let url = StreamCheckService::resolve_claude_stream_url(
|
||||
"https://example.com/v1",
|
||||
AuthStrategy::Bearer,
|
||||
"openai_chat",
|
||||
false,
|
||||
);
|
||||
|
||||
assert_eq!(url, "https://example.com/v1/chat/completions");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_claude_stream_url_for_openai_responses() {
|
||||
let url = StreamCheckService::resolve_claude_stream_url(
|
||||
"https://example.com/v1",
|
||||
AuthStrategy::Bearer,
|
||||
"openai_responses",
|
||||
false,
|
||||
);
|
||||
|
||||
assert_eq!(url, "https://example.com/v1/responses");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_claude_stream_url_for_anthropic() {
|
||||
let url = StreamCheckService::resolve_claude_stream_url(
|
||||
"https://api.anthropic.com",
|
||||
AuthStrategy::Anthropic,
|
||||
"anthropic",
|
||||
false,
|
||||
);
|
||||
|
||||
assert_eq!(url, "https://api.anthropic.com/v1/messages");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_codex_stream_urls_for_full_url_mode() {
|
||||
let urls = StreamCheckService::resolve_codex_stream_urls(
|
||||
"https://relay.example/custom/responses",
|
||||
true,
|
||||
);
|
||||
|
||||
assert_eq!(urls, vec!["https://relay.example/custom/responses"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_codex_stream_urls_for_v1_base() {
|
||||
let urls =
|
||||
StreamCheckService::resolve_codex_stream_urls("https://api.openai.com/v1", false);
|
||||
|
||||
assert_eq!(urls, vec!["https://api.openai.com/v1/responses"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_codex_stream_urls_for_origin_base() {
|
||||
let urls = StreamCheckService::resolve_codex_stream_urls("https://api.openai.com", false);
|
||||
|
||||
assert_eq!(
|
||||
urls,
|
||||
vec![
|
||||
"https://api.openai.com/responses",
|
||||
"https://api.openai.com/v1/responses",
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -204,10 +204,11 @@ pub async fn ensure_remote_directories(
|
||||
s if s == StatusCode::CREATED || s.is_success() => {
|
||||
log::info!("[WebDAV] MKCOL ok: {}", redact_url(&dir_url));
|
||||
}
|
||||
// 405 commonly means "already exists" on many WebDAV servers
|
||||
StatusCode::METHOD_NOT_ALLOWED => {}
|
||||
// Ambiguous — verify directory actually exists via PROPFIND
|
||||
s if s == StatusCode::CONFLICT || s.is_redirection() => {
|
||||
s if s == StatusCode::METHOD_NOT_ALLOWED
|
||||
|| s == StatusCode::CONFLICT
|
||||
|| s.is_redirection() =>
|
||||
{
|
||||
if !propfind_exists(&client, &dir_url, auth).await? {
|
||||
return Err(webdav_status_error("MKCOL", status, &dir_url));
|
||||
}
|
||||
|
||||
@@ -463,12 +463,10 @@ fn validate_manifest_compat(manifest: &SyncManifest, layout: RemoteLayout) -> Re
|
||||
return Err(localized(
|
||||
"webdav.sync.manifest_db_version_incompatible",
|
||||
format!(
|
||||
"远端数据库快照版本不兼容: db-v{} (本地 db-v{DB_COMPAT_VERSION})",
|
||||
db_compat_version
|
||||
"远端数据库快照版本不兼容: db-v{db_compat_version} (本地 db-v{DB_COMPAT_VERSION})"
|
||||
),
|
||||
format!(
|
||||
"Remote database snapshot version is incompatible: db-v{} (local db-v{DB_COMPAT_VERSION})",
|
||||
db_compat_version
|
||||
"Remote database snapshot version is incompatible: db-v{db_compat_version} (local db-v{DB_COMPAT_VERSION})"
|
||||
),
|
||||
));
|
||||
}
|
||||
@@ -476,12 +474,10 @@ fn validate_manifest_compat(manifest: &SyncManifest, layout: RemoteLayout) -> Re
|
||||
return Err(localized(
|
||||
"webdav.sync.manifest_db_version_incompatible",
|
||||
format!(
|
||||
"远端数据库快照版本不兼容: db-v{} (本地最高支持 db-v{DB_COMPAT_VERSION})",
|
||||
db_compat_version
|
||||
"远端数据库快照版本不兼容: db-v{db_compat_version} (本地最高支持 db-v{DB_COMPAT_VERSION})"
|
||||
),
|
||||
format!(
|
||||
"Remote database snapshot version is incompatible: db-v{} (local supports up to db-v{DB_COMPAT_VERSION})",
|
||||
db_compat_version
|
||||
"Remote database snapshot version is incompatible: db-v{db_compat_version} (local supports up to db-v{DB_COMPAT_VERSION})"
|
||||
),
|
||||
));
|
||||
}
|
||||
@@ -661,11 +657,8 @@ fn validate_artifact_size_limit(artifact_name: &str, size: u64) -> Result<(), Ap
|
||||
let max_mb = MAX_SYNC_ARTIFACT_BYTES / 1024 / 1024;
|
||||
return Err(localized(
|
||||
"webdav.sync.artifact_too_large",
|
||||
format!("artifact {artifact_name} 超过下载上限({} MB)", max_mb),
|
||||
format!(
|
||||
"Artifact {artifact_name} exceeds download limit ({} MB)",
|
||||
max_mb
|
||||
),
|
||||
format!("artifact {artifact_name} 超过下载上限({max_mb} MB)"),
|
||||
format!("Artifact {artifact_name} exceeds download limit ({max_mb} MB)"),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -350,8 +350,8 @@ fn copy_entry_with_total_limit<R: Read, W: Write>(
|
||||
let max_mb = max_total_bytes / 1024 / 1024;
|
||||
return Err(localized(
|
||||
"webdav.sync.skills_zip_too_large",
|
||||
format!("skills.zip 解压后体积超过上限({} MB)", max_mb),
|
||||
format!("skills.zip extracted size exceeds limit ({} MB)", max_mb),
|
||||
format!("skills.zip 解压后体积超过上限({max_mb} MB)"),
|
||||
format!("skills.zip extracted size exceeds limit ({max_mb} MB)"),
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
pub mod providers;
|
||||
pub mod terminal;
|
||||
|
||||
use serde::Serialize;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use providers::{claude, codex, gemini, openclaw, opencode};
|
||||
@@ -36,6 +36,25 @@ pub struct SessionMessage {
|
||||
pub ts: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DeleteSessionRequest {
|
||||
pub provider_id: String,
|
||||
pub session_id: String,
|
||||
pub source_path: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DeleteSessionOutcome {
|
||||
pub provider_id: String,
|
||||
pub session_id: String,
|
||||
pub source_path: String,
|
||||
pub success: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
pub fn scan_sessions() -> Vec<SessionMeta> {
|
||||
let (r1, r2, r3, r4, r5) = std::thread::scope(|s| {
|
||||
let h1 = s.spawn(codex::scan_sessions);
|
||||
@@ -69,6 +88,11 @@ pub fn scan_sessions() -> Vec<SessionMeta> {
|
||||
}
|
||||
|
||||
pub fn load_messages(provider_id: &str, source_path: &str) -> Result<Vec<SessionMessage>, String> {
|
||||
// OpenCode SQLite sessions use a "sqlite:" prefixed source_path
|
||||
if provider_id == "opencode" && source_path.starts_with("sqlite:") {
|
||||
return opencode::load_messages_sqlite(source_path);
|
||||
}
|
||||
|
||||
let path = Path::new(source_path);
|
||||
match provider_id {
|
||||
"codex" => codex::load_messages(path),
|
||||
@@ -85,10 +109,25 @@ pub fn delete_session(
|
||||
session_id: &str,
|
||||
source_path: &str,
|
||||
) -> Result<bool, String> {
|
||||
// OpenCode SQLite sessions bypass the file-based deletion path
|
||||
if provider_id == "opencode" && source_path.starts_with("sqlite:") {
|
||||
return opencode::delete_session_sqlite(session_id, source_path);
|
||||
}
|
||||
|
||||
let root = provider_root(provider_id)?;
|
||||
delete_session_with_root(provider_id, session_id, Path::new(source_path), &root)
|
||||
}
|
||||
|
||||
pub fn delete_sessions(requests: &[DeleteSessionRequest]) -> Vec<DeleteSessionOutcome> {
|
||||
collect_delete_session_outcomes(requests, |request| {
|
||||
delete_session(
|
||||
&request.provider_id,
|
||||
&request.session_id,
|
||||
&request.source_path,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn delete_session_with_root(
|
||||
provider_id: &str,
|
||||
session_id: &str,
|
||||
@@ -137,6 +176,41 @@ fn canonicalize_existing_path(path: &Path, label: &str) -> Result<PathBuf, Strin
|
||||
.map_err(|e| format!("Failed to resolve {label} {}: {e}", path.display()))
|
||||
}
|
||||
|
||||
fn collect_delete_session_outcomes<F>(
|
||||
requests: &[DeleteSessionRequest],
|
||||
mut deleter: F,
|
||||
) -> Vec<DeleteSessionOutcome>
|
||||
where
|
||||
F: FnMut(&DeleteSessionRequest) -> Result<bool, String>,
|
||||
{
|
||||
requests
|
||||
.iter()
|
||||
.map(|request| match deleter(request) {
|
||||
Ok(true) => DeleteSessionOutcome {
|
||||
provider_id: request.provider_id.clone(),
|
||||
session_id: request.session_id.clone(),
|
||||
source_path: request.source_path.clone(),
|
||||
success: true,
|
||||
error: None,
|
||||
},
|
||||
Ok(false) => DeleteSessionOutcome {
|
||||
provider_id: request.provider_id.clone(),
|
||||
session_id: request.session_id.clone(),
|
||||
source_path: request.source_path.clone(),
|
||||
success: false,
|
||||
error: Some("Session was not deleted".to_string()),
|
||||
},
|
||||
Err(error) => DeleteSessionOutcome {
|
||||
provider_id: request.provider_id.clone(),
|
||||
session_id: request.session_id.clone(),
|
||||
source_path: request.source_path.clone(),
|
||||
success: false,
|
||||
error: Some(error),
|
||||
},
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -165,4 +239,44 @@ mod tests {
|
||||
|
||||
assert!(err.contains("session source not found"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_delete_collects_successes_and_failures_in_order() {
|
||||
let requests = vec![
|
||||
DeleteSessionRequest {
|
||||
provider_id: "codex".to_string(),
|
||||
session_id: "s1".to_string(),
|
||||
source_path: "/tmp/s1".to_string(),
|
||||
},
|
||||
DeleteSessionRequest {
|
||||
provider_id: "claude".to_string(),
|
||||
session_id: "s2".to_string(),
|
||||
source_path: "/tmp/s2".to_string(),
|
||||
},
|
||||
DeleteSessionRequest {
|
||||
provider_id: "gemini".to_string(),
|
||||
session_id: "s3".to_string(),
|
||||
source_path: "/tmp/s3".to_string(),
|
||||
},
|
||||
];
|
||||
|
||||
let outcomes = collect_delete_session_outcomes(&requests, |request| {
|
||||
match request.session_id.as_str() {
|
||||
"s1" => Ok(true),
|
||||
"s2" => Err("boom".to_string()),
|
||||
_ => Ok(false),
|
||||
}
|
||||
});
|
||||
|
||||
assert_eq!(outcomes.len(), 3);
|
||||
assert!(outcomes[0].success);
|
||||
assert_eq!(outcomes[0].error, None);
|
||||
assert!(!outcomes[1].success);
|
||||
assert_eq!(outcomes[1].error.as_deref(), Some("boom"));
|
||||
assert!(!outcomes[2].success);
|
||||
assert_eq!(
|
||||
outcomes[2].error.as_deref(),
|
||||
Some("Session was not deleted")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,11 +52,25 @@ pub fn load_messages(path: &Path) -> Result<Vec<SessionMessage>, String> {
|
||||
None => continue,
|
||||
};
|
||||
|
||||
let role = message
|
||||
let mut role = message
|
||||
.get("role")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("unknown")
|
||||
.to_string();
|
||||
|
||||
// Claude wraps tool_result inside user messages; reclassify as "tool" role
|
||||
if role == "user" {
|
||||
if let Some(Value::Array(items)) = message.get("content") {
|
||||
let all_tool_results = !items.is_empty()
|
||||
&& items.iter().all(|item| {
|
||||
item.get("type").and_then(Value::as_str) == Some("tool_result")
|
||||
});
|
||||
if all_tool_results {
|
||||
role = "tool".to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let content = message.get("content").map(extract_text).unwrap_or_default();
|
||||
if content.trim().is_empty() {
|
||||
continue;
|
||||
@@ -268,4 +282,58 @@ mod tests {
|
||||
assert!(!path.exists());
|
||||
assert!(!sidecar.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_messages_tool_use_shows_as_assistant() {
|
||||
let temp = tempdir().expect("tempdir");
|
||||
let path = temp.path().join("session.jsonl");
|
||||
std::fs::write(
|
||||
&path,
|
||||
concat!(
|
||||
"{\"message\":{\"role\":\"assistant\",\"content\":[{\"type\":\"tool_use\",\"id\":\"toolu_1\",\"name\":\"Write\",\"input\":{\"file_path\":\"a.txt\"}}]},\"timestamp\":\"2026-03-06T10:00:00Z\"}\n",
|
||||
"{\"message\":{\"role\":\"user\",\"content\":[{\"type\":\"tool_result\",\"tool_use_id\":\"toolu_1\",\"content\":\"File written\"}]},\"timestamp\":\"2026-03-06T10:00:01Z\"}\n",
|
||||
),
|
||||
)
|
||||
.expect("write");
|
||||
|
||||
let msgs = load_messages(&path).expect("load");
|
||||
assert_eq!(msgs.len(), 2);
|
||||
assert_eq!(msgs[0].role, "assistant");
|
||||
assert!(msgs[0].content.contains("[Tool: Write]"));
|
||||
assert_eq!(msgs[1].role, "tool");
|
||||
assert_eq!(msgs[1].content, "File written");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_messages_mixed_text_and_tool_use() {
|
||||
let temp = tempdir().expect("tempdir");
|
||||
let path = temp.path().join("session.jsonl");
|
||||
std::fs::write(
|
||||
&path,
|
||||
"{\"message\":{\"role\":\"assistant\",\"content\":[{\"type\":\"text\",\"text\":\"Let me help.\"},{\"type\":\"tool_use\",\"id\":\"toolu_1\",\"name\":\"Read\",\"input\":{}}]},\"timestamp\":\"2026-03-06T10:00:00Z\"}\n",
|
||||
)
|
||||
.expect("write");
|
||||
|
||||
let msgs = load_messages(&path).expect("load");
|
||||
assert_eq!(msgs.len(), 1);
|
||||
assert_eq!(msgs[0].role, "assistant");
|
||||
assert!(msgs[0].content.contains("Let me help."));
|
||||
assert!(msgs[0].content.contains("[Tool: Read]"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_messages_mixed_user_tool_result_and_text_stays_user() {
|
||||
let temp = tempdir().expect("tempdir");
|
||||
let path = temp.path().join("session.jsonl");
|
||||
std::fs::write(
|
||||
&path,
|
||||
"{\"message\":{\"role\":\"user\",\"content\":[{\"type\":\"tool_result\",\"tool_use_id\":\"toolu_1\",\"content\":\"result\"},{\"type\":\"text\",\"text\":\"Please continue\"}]},\"timestamp\":\"2026-03-06T10:00:00Z\"}\n",
|
||||
)
|
||||
.expect("write");
|
||||
|
||||
let msgs = load_messages(&path).expect("load");
|
||||
assert_eq!(msgs.len(), 1);
|
||||
assert_eq!(msgs[0].role, "user");
|
||||
assert!(msgs[0].content.contains("Please continue"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,16 +59,37 @@ pub fn load_messages(path: &Path) -> Result<Vec<SessionMessage>, String> {
|
||||
None => continue,
|
||||
};
|
||||
|
||||
if payload.get("type").and_then(Value::as_str) != Some("message") {
|
||||
continue;
|
||||
}
|
||||
let payload_type = payload.get("type").and_then(Value::as_str).unwrap_or("");
|
||||
|
||||
// Codex uses separate payload types for tool interactions
|
||||
let (role, content) = match payload_type {
|
||||
"message" => {
|
||||
let role = payload
|
||||
.get("role")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("unknown")
|
||||
.to_string();
|
||||
let content = payload.get("content").map(extract_text).unwrap_or_default();
|
||||
(role, content)
|
||||
}
|
||||
"function_call" => {
|
||||
let name = payload
|
||||
.get("name")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("unknown");
|
||||
("assistant".to_string(), format!("[Tool: {name}]"))
|
||||
}
|
||||
"function_call_output" => {
|
||||
let output = payload
|
||||
.get("output")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
("tool".to_string(), output)
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
|
||||
let role = payload
|
||||
.get("role")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("unknown")
|
||||
.to_string();
|
||||
let content = payload.get("content").map(extract_text).unwrap_or_default();
|
||||
if content.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
@@ -239,4 +260,36 @@ mod tests {
|
||||
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_messages_includes_function_call_and_output() {
|
||||
let temp = tempdir().expect("tempdir");
|
||||
let path = temp.path().join("session.jsonl");
|
||||
std::fs::write(
|
||||
&path,
|
||||
concat!(
|
||||
"{\"timestamp\":\"2026-03-06T21:50:12Z\",\"type\":\"session_meta\",\"payload\":{\"id\":\"test-id\",\"cwd\":\"/tmp\"}}\n",
|
||||
"{\"timestamp\":\"2026-03-06T21:50:13Z\",\"type\":\"response_item\",\"payload\":{\"type\":\"message\",\"role\":\"user\",\"content\":\"list files\"}}\n",
|
||||
"{\"timestamp\":\"2026-03-06T21:50:14Z\",\"type\":\"response_item\",\"payload\":{\"type\":\"function_call\",\"name\":\"shell\",\"arguments\":\"{\\\"cmd\\\":[\\\"ls\\\"]}\",\"call_id\":\"call_1\"}}\n",
|
||||
"{\"timestamp\":\"2026-03-06T21:50:15Z\",\"type\":\"response_item\",\"payload\":{\"type\":\"function_call_output\",\"call_id\":\"call_1\",\"output\":\"file1.txt\\nfile2.txt\"}}\n",
|
||||
"{\"timestamp\":\"2026-03-06T21:50:16Z\",\"type\":\"response_item\",\"payload\":{\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"Done.\"}]}}\n",
|
||||
),
|
||||
)
|
||||
.expect("write");
|
||||
|
||||
let msgs = load_messages(&path).expect("load");
|
||||
assert_eq!(msgs.len(), 4);
|
||||
|
||||
assert_eq!(msgs[0].role, "user");
|
||||
assert_eq!(msgs[0].content, "list files");
|
||||
|
||||
assert_eq!(msgs[1].role, "assistant");
|
||||
assert!(msgs[1].content.contains("[Tool: shell]"));
|
||||
|
||||
assert_eq!(msgs[2].role, "tool");
|
||||
assert!(msgs[2].content.contains("file1.txt"));
|
||||
|
||||
assert_eq!(msgs[3].role, "assistant");
|
||||
assert_eq!(msgs[3].content, "Done.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,21 +60,47 @@ pub fn load_messages(path: &Path) -> Result<Vec<SessionMessage>, String> {
|
||||
|
||||
let mut result = Vec::new();
|
||||
for msg in messages {
|
||||
let content = match msg.get("content").and_then(Value::as_str) {
|
||||
Some(c) if !c.trim().is_empty() => c.to_string(),
|
||||
_ => continue,
|
||||
let role = match msg.get("type").and_then(Value::as_str) {
|
||||
Some("gemini") => "assistant",
|
||||
Some("user") => "user",
|
||||
Some("info") | Some("error") => continue,
|
||||
Some(_) | None => continue,
|
||||
};
|
||||
|
||||
let role = match msg.get("type").and_then(Value::as_str) {
|
||||
Some("gemini") => "assistant".to_string(),
|
||||
Some("user") => "user".to_string(),
|
||||
Some(other) => other.to_string(),
|
||||
None => continue,
|
||||
// Gemini content may be a plain string or an array of {text: ...} objects
|
||||
let mut content = match msg.get("content") {
|
||||
Some(Value::String(s)) => s.to_string(),
|
||||
Some(Value::Array(items)) => items
|
||||
.iter()
|
||||
.filter_map(|item| item.get("text").and_then(Value::as_str))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n"),
|
||||
_ => String::new(),
|
||||
};
|
||||
|
||||
// Append tool call names from the optional toolCalls array
|
||||
if let Some(Value::Array(calls)) = msg.get("toolCalls") {
|
||||
for call in calls {
|
||||
if let Some(name) = call.get("name").and_then(Value::as_str) {
|
||||
if !content.is_empty() {
|
||||
content.push('\n');
|
||||
}
|
||||
content.push_str(&format!("[Tool: {name}]"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if content.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let ts = msg.get("timestamp").and_then(parse_timestamp_to_ms);
|
||||
|
||||
result.push(SessionMessage { role, content, ts });
|
||||
result.push(SessionMessage {
|
||||
role: role.to_string(),
|
||||
content,
|
||||
ts,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
@@ -172,4 +198,55 @@ mod tests {
|
||||
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_messages_handles_array_content() {
|
||||
let temp = tempdir().expect("tempdir");
|
||||
let path = temp.path().join("session.json");
|
||||
std::fs::write(
|
||||
&path,
|
||||
r#"{
|
||||
"sessionId": "test",
|
||||
"messages": [
|
||||
{"id":"1","timestamp":"2026-03-06T10:00:00Z","type":"user","content":[{"text":"hello"}]},
|
||||
{"id":"2","timestamp":"2026-03-06T10:00:01Z","type":"gemini","content":"world"},
|
||||
{"id":"3","timestamp":"2026-03-06T10:00:02Z","type":"info","content":"system info"},
|
||||
{"id":"4","timestamp":"2026-03-06T10:00:03Z","type":"error","content":"MCP ERROR"}
|
||||
]
|
||||
}"#,
|
||||
)
|
||||
.expect("write");
|
||||
|
||||
let msgs = load_messages(&path).expect("load");
|
||||
assert_eq!(msgs.len(), 2);
|
||||
assert_eq!(msgs[0].role, "user");
|
||||
assert_eq!(msgs[0].content, "hello");
|
||||
assert_eq!(msgs[1].role, "assistant");
|
||||
assert_eq!(msgs[1].content, "world");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_messages_includes_tool_calls() {
|
||||
let temp = tempdir().expect("tempdir");
|
||||
let path = temp.path().join("session.json");
|
||||
std::fs::write(
|
||||
&path,
|
||||
r#"{
|
||||
"sessionId": "test",
|
||||
"messages": [
|
||||
{"id":"1","timestamp":"2026-03-10T08:24:50Z","type":"gemini","content":"","toolCalls":[{"id":"call_1","name":"web_search","args":{"query":"test"}}]},
|
||||
{"id":"2","timestamp":"2026-03-10T08:25:00Z","type":"gemini","content":"Here are the results.","toolCalls":[{"id":"call_2","name":"web_fetch","args":{"url":"http://example.com"}}]}
|
||||
]
|
||||
}"#,
|
||||
)
|
||||
.expect("write");
|
||||
|
||||
let msgs = load_messages(&path).expect("load");
|
||||
assert_eq!(msgs.len(), 2);
|
||||
assert_eq!(msgs[0].role, "assistant");
|
||||
assert!(msgs[0].content.contains("[Tool: web_search]"));
|
||||
assert_eq!(msgs[1].role, "assistant");
|
||||
assert!(msgs[1].content.contains("Here are the results."));
|
||||
assert!(msgs[1].content.contains("[Tool: web_fetch]"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use rusqlite::Connection;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::session_manager::{SessionMessage, SessionMeta};
|
||||
@@ -8,22 +9,59 @@ use super::utils::{parse_timestamp_to_ms, path_basename, truncate_summary};
|
||||
|
||||
const PROVIDER_ID: &str = "opencode";
|
||||
|
||||
/// Return the OpenCode data directory.
|
||||
/// Return the OpenCode base directory (`$XDG_DATA_HOME/opencode`).
|
||||
///
|
||||
/// Respects `XDG_DATA_HOME` on all platforms; falls back to
|
||||
/// `~/.local/share/opencode/storage/`.
|
||||
pub(crate) fn get_opencode_data_dir() -> PathBuf {
|
||||
/// `~/.local/share/opencode/`.
|
||||
pub(crate) fn get_opencode_base_dir() -> PathBuf {
|
||||
if let Ok(xdg) = std::env::var("XDG_DATA_HOME") {
|
||||
if !xdg.is_empty() {
|
||||
return PathBuf::from(xdg).join("opencode").join("storage");
|
||||
return PathBuf::from(xdg).join("opencode");
|
||||
}
|
||||
}
|
||||
dirs::home_dir()
|
||||
.map(|h| h.join(".local/share/opencode/storage"))
|
||||
.unwrap_or_else(|| PathBuf::from(".local/share/opencode/storage"))
|
||||
.map(|h| h.join(".local/share/opencode"))
|
||||
.unwrap_or_else(|| PathBuf::from(".local/share/opencode"))
|
||||
}
|
||||
|
||||
/// Return the OpenCode JSON storage directory (legacy flat-file layout).
|
||||
pub(crate) fn get_opencode_data_dir() -> PathBuf {
|
||||
get_opencode_base_dir().join("storage")
|
||||
}
|
||||
|
||||
fn get_opencode_db_path() -> PathBuf {
|
||||
get_opencode_base_dir().join("opencode.db")
|
||||
}
|
||||
|
||||
/// Scan sessions from both the legacy JSON files and the newer SQLite database,
|
||||
/// merging results with SQLite taking precedence on ID conflicts.
|
||||
pub fn scan_sessions() -> Vec<SessionMeta> {
|
||||
let json_sessions = scan_sessions_json();
|
||||
let sqlite_sessions = scan_sessions_sqlite();
|
||||
|
||||
if sqlite_sessions.is_empty() {
|
||||
return json_sessions;
|
||||
}
|
||||
if json_sessions.is_empty() {
|
||||
return sqlite_sessions;
|
||||
}
|
||||
|
||||
// Deduplicate: keep SQLite version when the same session_id exists in both
|
||||
let sqlite_ids: std::collections::HashSet<String> = sqlite_sessions
|
||||
.iter()
|
||||
.map(|s| s.session_id.clone())
|
||||
.collect();
|
||||
|
||||
let mut merged = sqlite_sessions;
|
||||
for s in json_sessions {
|
||||
if !sqlite_ids.contains(&s.session_id) {
|
||||
merged.push(s);
|
||||
}
|
||||
}
|
||||
merged
|
||||
}
|
||||
|
||||
fn scan_sessions_json() -> Vec<SessionMeta> {
|
||||
let storage = get_opencode_data_dir();
|
||||
let session_dir = storage.join("session");
|
||||
if !session_dir.exists() {
|
||||
@@ -42,6 +80,81 @@ pub fn scan_sessions() -> Vec<SessionMeta> {
|
||||
sessions
|
||||
}
|
||||
|
||||
/// Parse a SQLite source reference in the format `sqlite:<db_path>:<session_id>`.
|
||||
///
|
||||
/// Uses `rfind(":ses_")` to split the path from the session ID because the
|
||||
/// db path itself may contain colons (e.g. `C:\Users\...` on Windows).
|
||||
/// This relies on the OpenCode convention that session IDs start with `ses_`.
|
||||
fn parse_sqlite_source(source: &str) -> Option<(PathBuf, String)> {
|
||||
let rest = source.strip_prefix("sqlite:")?;
|
||||
let sep = rest.rfind(":ses_")?;
|
||||
let db_path = PathBuf::from(&rest[..sep]);
|
||||
let session_id = rest[sep + 1..].to_string();
|
||||
Some((db_path, session_id))
|
||||
}
|
||||
|
||||
fn scan_sessions_sqlite() -> Vec<SessionMeta> {
|
||||
let db_path = get_opencode_db_path();
|
||||
if !db_path.exists() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let conn = match Connection::open_with_flags(
|
||||
&db_path,
|
||||
rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
|
||||
) {
|
||||
Ok(c) => c,
|
||||
Err(_) => return Vec::new(),
|
||||
};
|
||||
|
||||
let mut stmt = match conn.prepare(
|
||||
"SELECT id, title, directory, time_created, time_updated FROM session ORDER BY time_updated DESC",
|
||||
) {
|
||||
Ok(s) => s,
|
||||
Err(_) => return Vec::new(),
|
||||
};
|
||||
|
||||
let db_display = db_path.display().to_string();
|
||||
|
||||
let iter = match stmt.query_map([], |row| {
|
||||
let session_id: String = row.get(0)?;
|
||||
let title: String = row.get(1)?;
|
||||
let directory: String = row.get(2)?;
|
||||
let created: i64 = row.get(3)?;
|
||||
let updated: i64 = row.get(4)?;
|
||||
Ok((session_id, title, directory, created, updated))
|
||||
}) {
|
||||
Ok(rows) => rows,
|
||||
Err(_) => return Vec::new(),
|
||||
};
|
||||
|
||||
let mut sessions = Vec::new();
|
||||
for row in iter.flatten() {
|
||||
let (session_id, title, directory, created, updated) = row;
|
||||
let display_title = if title.is_empty() {
|
||||
path_basename(&directory)
|
||||
} else {
|
||||
Some(title)
|
||||
};
|
||||
sessions.push(SessionMeta {
|
||||
provider_id: PROVIDER_ID.to_string(),
|
||||
session_id: session_id.clone(),
|
||||
title: display_title.clone(),
|
||||
summary: display_title,
|
||||
project_dir: if directory.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(directory)
|
||||
},
|
||||
created_at: Some(created),
|
||||
last_active_at: Some(updated),
|
||||
source_path: Some(format!("sqlite:{db_display}:{session_id}")),
|
||||
resume_command: Some(format!("opencode session resume {session_id}")),
|
||||
});
|
||||
}
|
||||
sessions
|
||||
}
|
||||
|
||||
pub fn load_messages(path: &Path) -> Result<Vec<SessionMessage>, String> {
|
||||
// `path` is the message directory: storage/message/{sessionID}/
|
||||
if !path.is_dir() {
|
||||
@@ -111,6 +224,95 @@ pub fn load_messages(path: &Path) -> Result<Vec<SessionMessage>, String> {
|
||||
Ok(messages)
|
||||
}
|
||||
|
||||
/// Load messages from the OpenCode SQLite database for a given source reference.
|
||||
/// Joins the `message` and `part` tables in memory to reconstruct full messages.
|
||||
pub fn load_messages_sqlite(source: &str) -> Result<Vec<SessionMessage>, String> {
|
||||
let (db_path, session_id) = parse_sqlite_source(source)
|
||||
.ok_or_else(|| format!("Invalid SQLite source reference: {source}"))?;
|
||||
|
||||
let conn = Connection::open_with_flags(
|
||||
&db_path,
|
||||
rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
|
||||
)
|
||||
.map_err(|e| format!("Failed to open OpenCode database: {e}"))?;
|
||||
|
||||
let mut msg_stmt = conn
|
||||
.prepare(
|
||||
"SELECT id, time_created, data FROM message WHERE session_id = ?1 ORDER BY time_created ASC",
|
||||
)
|
||||
.map_err(|e| format!("Failed to prepare message query: {e}"))?;
|
||||
|
||||
let msg_rows = msg_stmt
|
||||
.query_map([session_id.as_str()], |row| {
|
||||
let id: String = row.get(0)?;
|
||||
let ts: i64 = row.get(1)?;
|
||||
let data: String = row.get(2)?;
|
||||
Ok((id, ts, data))
|
||||
})
|
||||
.map_err(|e| format!("Failed to query messages: {e}"))?;
|
||||
|
||||
let mut part_stmt = conn
|
||||
.prepare(
|
||||
"SELECT message_id, data FROM part WHERE session_id = ?1 ORDER BY time_created ASC",
|
||||
)
|
||||
.map_err(|e| format!("Failed to prepare part query: {e}"))?;
|
||||
|
||||
let part_rows = part_stmt
|
||||
.query_map([session_id.as_str()], |row| {
|
||||
let message_id: String = row.get(0)?;
|
||||
let data: String = row.get(1)?;
|
||||
Ok((message_id, data))
|
||||
})
|
||||
.map_err(|e| format!("Failed to query parts: {e}"))?;
|
||||
|
||||
let mut parts_map: std::collections::HashMap<String, Vec<String>> =
|
||||
std::collections::HashMap::new();
|
||||
for part in part_rows.flatten() {
|
||||
let (message_id, data) = part;
|
||||
parts_map.entry(message_id).or_default().push(data);
|
||||
}
|
||||
|
||||
let mut messages = Vec::new();
|
||||
for row in msg_rows.flatten() {
|
||||
let (msg_id, ts, data) = row;
|
||||
let msg_value: Value = match serde_json::from_str(&data) {
|
||||
Ok(v) => v,
|
||||
Err(_) => continue,
|
||||
};
|
||||
let role = msg_value
|
||||
.get("role")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("unknown")
|
||||
.to_string();
|
||||
|
||||
let mut texts = Vec::new();
|
||||
if let Some(parts) = parts_map.get(&msg_id) {
|
||||
for part_data in parts {
|
||||
let part_value: Value = match serde_json::from_str(part_data) {
|
||||
Ok(v) => v,
|
||||
Err(_) => continue,
|
||||
};
|
||||
if let Some(text) = extract_part_text(&part_value) {
|
||||
texts.push(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let content = texts.join("\n");
|
||||
if content.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
messages.push(SessionMessage {
|
||||
role,
|
||||
content,
|
||||
ts: Some(ts),
|
||||
});
|
||||
}
|
||||
|
||||
Ok(messages)
|
||||
}
|
||||
|
||||
pub fn delete_session(storage: &Path, path: &Path, session_id: &str) -> Result<bool, String> {
|
||||
if path.file_name().and_then(|name| name.to_str()) != Some(session_id) {
|
||||
return Err(format!(
|
||||
@@ -176,6 +378,48 @@ pub fn delete_session(storage: &Path, path: &Path, session_id: &str) -> Result<b
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Delete a session from the OpenCode SQLite database.
|
||||
pub fn delete_session_sqlite(session_id: &str, source: &str) -> Result<bool, String> {
|
||||
let (db_path, ref_session_id) = parse_sqlite_source(source)
|
||||
.ok_or_else(|| format!("Invalid SQLite source reference: {source}"))?;
|
||||
let db_path = db_path
|
||||
.canonicalize()
|
||||
.map_err(|e| format!("Failed to canonicalize SQLite database path: {e}"))?;
|
||||
let expected_db_path = get_opencode_db_path()
|
||||
.canonicalize()
|
||||
.map_err(|e| format!("Failed to canonicalize expected OpenCode database path: {e}"))?;
|
||||
|
||||
if ref_session_id != session_id {
|
||||
return Err(format!(
|
||||
"OpenCode SQLite session ID mismatch: expected {session_id}, found {ref_session_id}"
|
||||
));
|
||||
}
|
||||
if db_path != expected_db_path {
|
||||
return Err("SQLite path does not match expected OpenCode database".to_string());
|
||||
}
|
||||
|
||||
let conn =
|
||||
Connection::open(&db_path).map_err(|e| format!("Failed to open OpenCode database: {e}"))?;
|
||||
|
||||
let tx = conn
|
||||
.unchecked_transaction()
|
||||
.map_err(|e| format!("Failed to begin transaction: {e}"))?;
|
||||
|
||||
tx.execute("DELETE FROM part WHERE session_id = ?1", [session_id])
|
||||
.map_err(|e| format!("Failed to delete OpenCode parts: {e}"))?;
|
||||
tx.execute("DELETE FROM message WHERE session_id = ?1", [session_id])
|
||||
.map_err(|e| format!("Failed to delete OpenCode messages: {e}"))?;
|
||||
|
||||
let deleted = tx
|
||||
.execute("DELETE FROM session WHERE id = ?1", [session_id])
|
||||
.map_err(|e| format!("Failed to delete OpenCode session: {e}"))?;
|
||||
|
||||
tx.commit()
|
||||
.map_err(|e| format!("Failed to commit session deletion: {e}"))?;
|
||||
|
||||
Ok(deleted > 0)
|
||||
}
|
||||
|
||||
fn parse_session(storage: &Path, path: &Path) -> Option<SessionMeta> {
|
||||
let data = std::fs::read_to_string(path).ok()?;
|
||||
let value: Value = serde_json::from_str(&data).ok()?;
|
||||
@@ -286,6 +530,24 @@ fn get_first_user_summary(storage: &Path, session_id: &str) -> Option<String> {
|
||||
}
|
||||
|
||||
/// Collect text content from all parts in a part directory.
|
||||
fn extract_part_text(part_value: &Value) -> Option<String> {
|
||||
match part_value.get("type").and_then(Value::as_str) {
|
||||
Some("text") => part_value
|
||||
.get("text")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|t| !t.trim().is_empty())
|
||||
.map(|t| t.to_string()),
|
||||
Some("tool") => {
|
||||
let tool = part_value
|
||||
.get("tool")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("unknown");
|
||||
Some(format!("[Tool: {tool}]"))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_parts_text(part_dir: &Path) -> String {
|
||||
if !part_dir.is_dir() {
|
||||
return String::new();
|
||||
@@ -305,15 +567,8 @@ fn collect_parts_text(part_dir: &Path) -> String {
|
||||
Err(_) => continue,
|
||||
};
|
||||
|
||||
// Only include text-type parts
|
||||
if value.get("type").and_then(Value::as_str) != Some("text") {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(text) = value.get("text").and_then(Value::as_str) {
|
||||
if !text.trim().is_empty() {
|
||||
texts.push(text.to_string());
|
||||
}
|
||||
if let Some(text) = extract_part_text(&value) {
|
||||
texts.push(text);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -370,8 +625,47 @@ fn remove_dir_all_if_exists(path: &Path) -> std::io::Result<()> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rusqlite::Connection;
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
use tempfile::tempdir;
|
||||
|
||||
fn opencode_env_lock() -> &'static Mutex<()> {
|
||||
static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
|
||||
LOCK.get_or_init(|| Mutex::new(()))
|
||||
}
|
||||
|
||||
fn create_sqlite_schema(conn: &Connection) {
|
||||
conn.execute_batch(
|
||||
"
|
||||
PRAGMA foreign_keys = ON;
|
||||
CREATE TABLE session (
|
||||
id TEXT PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
directory TEXT NOT NULL,
|
||||
time_created INTEGER NOT NULL,
|
||||
time_updated INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE message (
|
||||
id TEXT PRIMARY KEY,
|
||||
session_id TEXT NOT NULL,
|
||||
time_created INTEGER NOT NULL,
|
||||
data TEXT NOT NULL,
|
||||
FOREIGN KEY(session_id) REFERENCES session(id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE TABLE part (
|
||||
id TEXT PRIMARY KEY,
|
||||
session_id TEXT NOT NULL,
|
||||
message_id TEXT NOT NULL,
|
||||
time_created INTEGER NOT NULL,
|
||||
data TEXT NOT NULL,
|
||||
FOREIGN KEY(session_id) REFERENCES session(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY(message_id) REFERENCES message(id) ON DELETE CASCADE
|
||||
);
|
||||
",
|
||||
)
|
||||
.expect("create sqlite schema");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_session_removes_session_diff_messages_and_parts() {
|
||||
let temp = tempdir().expect("tempdir");
|
||||
@@ -432,4 +726,272 @@ mod tests {
|
||||
.join(format!("{project_id}.json"))
|
||||
.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_messages_includes_tool_parts() {
|
||||
let temp = tempdir().expect("tempdir");
|
||||
let storage = temp.path();
|
||||
let session_id = "ses_test";
|
||||
let msg_id = "msg_1";
|
||||
|
||||
let msg_dir = storage.join("message").join(session_id);
|
||||
let part_dir = storage.join("part").join(msg_id);
|
||||
std::fs::create_dir_all(&msg_dir).expect("create msg dir");
|
||||
std::fs::create_dir_all(&part_dir).expect("create part dir");
|
||||
|
||||
std::fs::write(
|
||||
msg_dir.join(format!("{msg_id}.json")),
|
||||
r#"{"id":"msg_1","role":"assistant","time":{"created":"2026-03-06T10:00:00Z"}}"#,
|
||||
)
|
||||
.expect("write msg");
|
||||
|
||||
std::fs::write(
|
||||
part_dir.join("prt_1.json"),
|
||||
r#"{"id":"prt_1","type":"tool","tool":"bash","state":{"status":"completed","input":{"command":"ls"},"output":"file.txt"}}"#,
|
||||
)
|
||||
.expect("write tool part");
|
||||
|
||||
std::fs::write(
|
||||
part_dir.join("prt_2.json"),
|
||||
r#"{"id":"prt_2","type":"text","text":"Here are the files."}"#,
|
||||
)
|
||||
.expect("write text part");
|
||||
|
||||
let msgs = load_messages(&msg_dir).expect("load");
|
||||
assert_eq!(msgs.len(), 1);
|
||||
assert_eq!(msgs[0].role, "assistant");
|
||||
assert!(msgs[0].content.contains("[Tool: bash]"));
|
||||
assert!(msgs[0].content.contains("Here are the files."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_sqlite_source_accepts_valid_references() {
|
||||
let parsed = parse_sqlite_source("sqlite:/tmp/opencode.db:ses_123").expect("valid source");
|
||||
|
||||
assert_eq!(parsed.0, PathBuf::from("/tmp/opencode.db"));
|
||||
assert_eq!(parsed.1, "ses_123");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_sqlite_source_rejects_invalid_references() {
|
||||
assert!(parse_sqlite_source("/tmp/opencode.db:ses_123").is_none());
|
||||
assert!(parse_sqlite_source("sqlite:/tmp/opencode.db:msg_123").is_none());
|
||||
assert!(parse_sqlite_source("sqlite:/tmp/opencode.db").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[allow(deprecated)] // set_var/remove_var deprecated since Rust 1.81; safe here under mutex
|
||||
fn scan_sessions_sqlite_reads_temp_database() {
|
||||
let _guard = opencode_env_lock().lock().expect("lock");
|
||||
let temp = tempdir().expect("tempdir");
|
||||
let original_xdg = std::env::var_os("XDG_DATA_HOME");
|
||||
std::env::set_var("XDG_DATA_HOME", temp.path());
|
||||
|
||||
let base_dir = temp.path().join("opencode");
|
||||
std::fs::create_dir_all(&base_dir).expect("create base dir");
|
||||
let db_path = base_dir.join("opencode.db");
|
||||
let conn = Connection::open(&db_path).expect("open sqlite db");
|
||||
create_sqlite_schema(&conn);
|
||||
|
||||
conn.execute(
|
||||
"INSERT INTO session (id, title, directory, time_created, time_updated) VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
("ses_1", "", "/tmp/project-a", 1_771_061_953_033_i64, 1_771_061_954_033_i64),
|
||||
)
|
||||
.expect("insert session 1");
|
||||
conn.execute(
|
||||
"INSERT INTO session (id, title, directory, time_created, time_updated) VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
("ses_2", "Named Session", "/tmp/project-b", 1_771_061_950_000_i64, 1_771_061_955_000_i64),
|
||||
)
|
||||
.expect("insert session 2");
|
||||
drop(conn);
|
||||
|
||||
let sessions = scan_sessions_sqlite();
|
||||
|
||||
#[allow(deprecated)]
|
||||
if let Some(value) = original_xdg {
|
||||
std::env::set_var("XDG_DATA_HOME", value);
|
||||
} else {
|
||||
std::env::remove_var("XDG_DATA_HOME");
|
||||
}
|
||||
|
||||
assert_eq!(sessions.len(), 2);
|
||||
assert_eq!(sessions[0].session_id, "ses_2");
|
||||
assert_eq!(sessions[0].title.as_deref(), Some("Named Session"));
|
||||
assert_eq!(sessions[1].session_id, "ses_1");
|
||||
assert_eq!(sessions[1].title.as_deref(), Some("project-a"));
|
||||
assert_eq!(sessions[1].project_dir.as_deref(), Some("/tmp/project-a"));
|
||||
let expected_source = format!("sqlite:{}:ses_1", db_path.display());
|
||||
assert_eq!(
|
||||
sessions[1].source_path.as_deref(),
|
||||
Some(expected_source.as_str())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_messages_sqlite_reads_messages_and_parts() {
|
||||
let temp = tempdir().expect("tempdir");
|
||||
let db_path = temp.path().join("opencode.db");
|
||||
let conn = Connection::open(&db_path).expect("open sqlite db");
|
||||
create_sqlite_schema(&conn);
|
||||
|
||||
conn.execute(
|
||||
"INSERT INTO session (id, title, directory, time_created, time_updated) VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
("ses_1", "Session", "/tmp/project-a", 1000_i64, 3000_i64),
|
||||
)
|
||||
.expect("insert session");
|
||||
conn.execute(
|
||||
"INSERT INTO message (id, session_id, time_created, data) VALUES (?1, ?2, ?3, ?4)",
|
||||
("msg_1", "ses_1", 1000_i64, r#"{"role":"user"}"#),
|
||||
)
|
||||
.expect("insert message 1");
|
||||
conn.execute(
|
||||
"INSERT INTO message (id, session_id, time_created, data) VALUES (?1, ?2, ?3, ?4)",
|
||||
("msg_2", "ses_1", 2000_i64, r#"{"role":"assistant"}"#),
|
||||
)
|
||||
.expect("insert message 2");
|
||||
conn.execute(
|
||||
"INSERT INTO part (id, session_id, message_id, time_created, data) VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
("prt_1", "ses_1", "msg_1", 1000_i64, r#"{"type":"text","text":"Hello"}"#),
|
||||
)
|
||||
.expect("insert part 1");
|
||||
conn.execute(
|
||||
"INSERT INTO part (id, session_id, message_id, time_created, data) VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
(
|
||||
"prt_2",
|
||||
"ses_1",
|
||||
"msg_2",
|
||||
2000_i64,
|
||||
r#"{"type":"tool","tool":"bash"}"#,
|
||||
),
|
||||
)
|
||||
.expect("insert part 2");
|
||||
conn.execute(
|
||||
"INSERT INTO part (id, session_id, message_id, time_created, data) VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
(
|
||||
"prt_3",
|
||||
"ses_1",
|
||||
"msg_2",
|
||||
2001_i64,
|
||||
r#"{"type":"text","text":"Done"}"#,
|
||||
),
|
||||
)
|
||||
.expect("insert part 3");
|
||||
drop(conn);
|
||||
|
||||
let source = format!("sqlite:{}:ses_1", db_path.display());
|
||||
let messages = load_messages_sqlite(&source).expect("load sqlite messages");
|
||||
|
||||
assert_eq!(messages.len(), 2);
|
||||
assert_eq!(messages[0].role, "user");
|
||||
assert_eq!(messages[0].content, "Hello");
|
||||
assert_eq!(messages[0].ts, Some(1000));
|
||||
assert_eq!(messages[1].role, "assistant");
|
||||
assert_eq!(messages[1].content, "[Tool: bash]\nDone");
|
||||
assert_eq!(messages[1].ts, Some(2000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_session_sqlite_removes_session() {
|
||||
let _guard = opencode_env_lock().lock().expect("lock");
|
||||
let temp = tempdir().expect("tempdir");
|
||||
let original_xdg = std::env::var_os("XDG_DATA_HOME");
|
||||
#[allow(deprecated)]
|
||||
std::env::set_var("XDG_DATA_HOME", temp.path());
|
||||
|
||||
let base_dir = temp.path().join("opencode");
|
||||
std::fs::create_dir_all(&base_dir).expect("create base dir");
|
||||
let db_path = base_dir.join("opencode.db");
|
||||
let conn = Connection::open(&db_path).expect("open sqlite db");
|
||||
create_sqlite_schema(&conn);
|
||||
|
||||
conn.execute(
|
||||
"INSERT INTO session (id, title, directory, time_created, time_updated) VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
("ses_1", "Session", "/tmp/project-a", 1000_i64, 3000_i64),
|
||||
)
|
||||
.expect("insert session");
|
||||
conn.execute(
|
||||
"INSERT INTO message (id, session_id, time_created, data) VALUES (?1, ?2, ?3, ?4)",
|
||||
("msg_1", "ses_1", 1000_i64, r#"{"role":"user"}"#),
|
||||
)
|
||||
.expect("insert message");
|
||||
conn.execute(
|
||||
"INSERT INTO part (id, session_id, message_id, time_created, data) VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
("prt_1", "ses_1", "msg_1", 1000_i64, r#"{"type":"text","text":"Hello"}"#),
|
||||
)
|
||||
.expect("insert part");
|
||||
drop(conn);
|
||||
|
||||
let source = format!("sqlite:{}:ses_1", db_path.display());
|
||||
let deleted = delete_session_sqlite("ses_1", &source).expect("delete sqlite session");
|
||||
assert!(deleted);
|
||||
|
||||
let conn = Connection::open(&db_path).expect("re-open sqlite db");
|
||||
let remaining_sessions: i64 = conn
|
||||
.query_row(
|
||||
"SELECT COUNT(*) FROM session WHERE id = 'ses_1'",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.expect("count sessions");
|
||||
let remaining_messages: i64 = conn
|
||||
.query_row(
|
||||
"SELECT COUNT(*) FROM message WHERE session_id = 'ses_1'",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.expect("count messages");
|
||||
let remaining_parts: i64 = conn
|
||||
.query_row(
|
||||
"SELECT COUNT(*) FROM part WHERE session_id = 'ses_1'",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.expect("count parts");
|
||||
|
||||
assert_eq!(remaining_sessions, 0);
|
||||
assert_eq!(remaining_messages, 0);
|
||||
assert_eq!(remaining_parts, 0);
|
||||
|
||||
#[allow(deprecated)]
|
||||
if let Some(value) = original_xdg {
|
||||
std::env::set_var("XDG_DATA_HOME", value);
|
||||
} else {
|
||||
std::env::remove_var("XDG_DATA_HOME");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_session_sqlite_rejects_foreign_db_path() {
|
||||
let _guard = opencode_env_lock().lock().expect("lock");
|
||||
let temp = tempdir().expect("tempdir");
|
||||
let original_xdg = std::env::var_os("XDG_DATA_HOME");
|
||||
#[allow(deprecated)]
|
||||
std::env::set_var("XDG_DATA_HOME", temp.path());
|
||||
|
||||
let expected_base_dir = temp.path().join("opencode");
|
||||
std::fs::create_dir_all(&expected_base_dir).expect("create expected base dir");
|
||||
let expected_db_path = expected_base_dir.join("opencode.db");
|
||||
Connection::open(&expected_db_path).expect("create expected sqlite db");
|
||||
|
||||
let db_path = temp.path().join("foreign.db");
|
||||
let conn = Connection::open(&db_path).expect("open sqlite db");
|
||||
create_sqlite_schema(&conn);
|
||||
conn.execute(
|
||||
"INSERT INTO session (id, title, directory, time_created, time_updated) VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
("ses_1", "Session", "/tmp/project", 1000_i64, 3000_i64),
|
||||
)
|
||||
.expect("insert session");
|
||||
drop(conn);
|
||||
|
||||
let source = format!("sqlite:{}:ses_1", db_path.display());
|
||||
let err = delete_session_sqlite("ses_1", &source).expect_err("should reject foreign db");
|
||||
assert!(err.contains("expected OpenCode database"));
|
||||
|
||||
#[allow(deprecated)]
|
||||
if let Some(value) = original_xdg {
|
||||
std::env::set_var("XDG_DATA_HOME", value);
|
||||
} else {
|
||||
std::env::remove_var("XDG_DATA_HOME");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,6 +46,15 @@ pub fn read_head_tail_lines(
|
||||
}
|
||||
|
||||
pub fn parse_timestamp_to_ms(value: &Value) -> Option<i64> {
|
||||
// Integer: milliseconds (>1e12) or seconds
|
||||
if let Some(n) = value.as_i64() {
|
||||
return Some(if n > 1_000_000_000_000 { n } else { n * 1000 });
|
||||
}
|
||||
if let Some(n) = value.as_f64() {
|
||||
let n = n as i64;
|
||||
return Some(if n > 1_000_000_000_000 { n } else { n * 1000 });
|
||||
}
|
||||
// RFC3339 string
|
||||
let raw = value.as_str()?;
|
||||
DateTime::parse_from_rfc3339(raw)
|
||||
.ok()
|
||||
@@ -71,6 +80,28 @@ pub fn extract_text(content: &Value) -> String {
|
||||
}
|
||||
|
||||
fn extract_text_from_item(item: &Value) -> Option<String> {
|
||||
let item_type = item.get("type").and_then(Value::as_str).unwrap_or("");
|
||||
|
||||
// tool_use: show tool name
|
||||
if item_type == "tool_use" {
|
||||
let name = item
|
||||
.get("name")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("unknown");
|
||||
return Some(format!("[Tool: {name}]"));
|
||||
}
|
||||
|
||||
// tool_result: extract nested content
|
||||
if item_type == "tool_result" {
|
||||
if let Some(content) = item.get("content") {
|
||||
let text = extract_text(content);
|
||||
if !text.is_empty() {
|
||||
return Some(text);
|
||||
}
|
||||
}
|
||||
return None;
|
||||
}
|
||||
|
||||
if let Some(text) = item.get("text").and_then(|v| v.as_str()) {
|
||||
return Some(text.to_string());
|
||||
}
|
||||
@@ -119,3 +150,25 @@ pub fn path_basename(value: &str) -> Option<String> {
|
||||
.filter(|segment| !segment.is_empty())?;
|
||||
Some(last.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn parse_timestamp_to_ms_supports_integers_and_rfc3339() {
|
||||
assert_eq!(
|
||||
parse_timestamp_to_ms(&json!(1_771_061_953_033_i64)),
|
||||
Some(1_771_061_953_033)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_timestamp_to_ms(&json!(1_771_061_953_i64)),
|
||||
Some(1_771_061_953_000)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_timestamp_to_ms(&json!("1970-01-01T00:00:01Z")),
|
||||
Some(1_000)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,39 +77,10 @@ end tell"#
|
||||
}
|
||||
|
||||
fn launch_ghostty(command: &str, cwd: Option<&str>) -> Result<(), String> {
|
||||
// Ghostty usage: open -na Ghostty --args +work-dir=... -e shell -c command
|
||||
|
||||
// Using `open` to launch.
|
||||
let mut args = vec!["-na", "Ghostty", "--args"];
|
||||
|
||||
// Ghostty uses --working-directory for working directory (or +work-dir, but --working-directory is standard in newer versions/compat)
|
||||
// Note: The user's error output didn't show the working dir arg failure, so we assume flag is okay or we stick to compatible ones.
|
||||
// Documentation says --working-directory is supported in CLI.
|
||||
let work_dir_arg = if let Some(dir) = cwd {
|
||||
format!("--working-directory={dir}")
|
||||
} else {
|
||||
"".to_string()
|
||||
};
|
||||
|
||||
if !work_dir_arg.is_empty() {
|
||||
args.push(&work_dir_arg);
|
||||
}
|
||||
|
||||
// Command execution
|
||||
args.push("-e");
|
||||
|
||||
// We pass the command and its arguments separately.
|
||||
// The previous issue was passing the entire "cmd args" string as a single argument to -e,
|
||||
// which led Ghostty to look for a binary named "cmd args".
|
||||
// Splitting by whitespace allows Ghostty to see ["cmd", "args"].
|
||||
// Note: This assumes simple commands without quoted arguments containing spaces.
|
||||
let full_command = build_shell_command(command, None);
|
||||
for part in full_command.split_whitespace() {
|
||||
args.push(part);
|
||||
}
|
||||
let args = build_ghostty_args(command, cwd);
|
||||
|
||||
let status = Command::new("open")
|
||||
.args(&args)
|
||||
.args(args.iter().map(String::as_str))
|
||||
.status()
|
||||
.map_err(|e| format!("Failed to launch Ghostty: {e}"))?;
|
||||
|
||||
@@ -120,6 +91,40 @@ fn launch_ghostty(command: &str, cwd: Option<&str>) -> Result<(), String> {
|
||||
}
|
||||
}
|
||||
|
||||
fn build_ghostty_args(command: &str, cwd: Option<&str>) -> Vec<String> {
|
||||
let input = ghostty_raw_input(command);
|
||||
|
||||
let mut args = vec![
|
||||
"-na".to_string(),
|
||||
"Ghostty".to_string(),
|
||||
"--args".to_string(),
|
||||
"--quit-after-last-window-closed=true".to_string(),
|
||||
];
|
||||
|
||||
if let Some(dir) = cwd {
|
||||
if !dir.trim().is_empty() {
|
||||
args.push(format!("--working-directory={dir}"));
|
||||
}
|
||||
}
|
||||
|
||||
args.push(format!("--input={input}"));
|
||||
args
|
||||
}
|
||||
|
||||
fn ghostty_raw_input(command: &str) -> String {
|
||||
let mut escaped = String::from("raw:");
|
||||
for ch in command.chars() {
|
||||
match ch {
|
||||
'\\' => escaped.push_str("\\\\"),
|
||||
'\n' => escaped.push_str("\\n"),
|
||||
'\r' => escaped.push_str("\\r"),
|
||||
_ => escaped.push(ch),
|
||||
}
|
||||
}
|
||||
escaped.push_str("\\n");
|
||||
escaped
|
||||
}
|
||||
|
||||
fn launch_kitty(command: &str, cwd: Option<&str>) -> Result<(), String> {
|
||||
let full_command = build_shell_command(command, cwd);
|
||||
|
||||
@@ -255,3 +260,49 @@ fn shell_escape(value: &str) -> String {
|
||||
fn escape_osascript(value: &str) -> String {
|
||||
value.replace('\\', "\\\\").replace('"', "\\\"")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ghostty_uses_shell_mode_for_resume_commands() {
|
||||
let args = build_ghostty_args("claude --resume abc-123", Some("/tmp/project dir"));
|
||||
|
||||
assert_eq!(
|
||||
args,
|
||||
vec![
|
||||
"-na",
|
||||
"Ghostty",
|
||||
"--args",
|
||||
"--quit-after-last-window-closed=true",
|
||||
"--working-directory=/tmp/project dir",
|
||||
"--input=raw:claude --resume abc-123\\n",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ghostty_keeps_command_without_cwd_prefix_when_not_provided() {
|
||||
let args = build_ghostty_args("claude --resume abc-123", None);
|
||||
|
||||
assert_eq!(
|
||||
args,
|
||||
vec![
|
||||
"-na",
|
||||
"Ghostty",
|
||||
"--args",
|
||||
"--quit-after-last-window-closed=true",
|
||||
"--input=raw:claude --resume abc-123\\n",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ghostty_escapes_newlines_and_backslashes_in_input() {
|
||||
assert_eq!(
|
||||
ghostty_raw_input("echo foo\\\\bar\npwd"),
|
||||
"raw:echo foo\\\\\\\\bar\\npwd\\n"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -584,17 +584,14 @@ pub fn get_current_provider(app_type: &AppType) -> Option<String> {
|
||||
/// 这是设备级别的设置,不随数据库同步。
|
||||
/// 传入 `None` 会清除当前供应商设置。
|
||||
pub fn set_current_provider(app_type: &AppType, id: Option<&str>) -> Result<(), AppError> {
|
||||
let mut settings = get_settings();
|
||||
|
||||
match app_type {
|
||||
AppType::Claude => settings.current_provider_claude = id.map(|s| s.to_string()),
|
||||
AppType::Codex => settings.current_provider_codex = id.map(|s| s.to_string()),
|
||||
AppType::Gemini => settings.current_provider_gemini = id.map(|s| s.to_string()),
|
||||
AppType::OpenCode => settings.current_provider_opencode = id.map(|s| s.to_string()),
|
||||
AppType::OpenClaw => settings.current_provider_openclaw = id.map(|s| s.to_string()),
|
||||
}
|
||||
|
||||
update_settings(settings)
|
||||
let id_owned = id.map(|s| s.to_string());
|
||||
mutate_settings(|settings| match app_type {
|
||||
AppType::Claude => settings.current_provider_claude = id_owned.clone(),
|
||||
AppType::Codex => settings.current_provider_codex = id_owned.clone(),
|
||||
AppType::Gemini => settings.current_provider_gemini = id_owned.clone(),
|
||||
AppType::OpenCode => settings.current_provider_opencode = id_owned.clone(),
|
||||
AppType::OpenClaw => settings.current_provider_openclaw = id_owned.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// 获取有效的当前供应商 ID(验证存在性)
|
||||
|
||||
@@ -14,6 +14,7 @@ use crate::store::AppState;
|
||||
pub struct TrayTexts {
|
||||
pub show_main: &'static str,
|
||||
pub no_provider_hint: &'static str,
|
||||
pub lightweight_mode: &'static str,
|
||||
pub quit: &'static str,
|
||||
pub _auto_label: &'static str,
|
||||
}
|
||||
@@ -24,6 +25,7 @@ impl TrayTexts {
|
||||
"en" => Self {
|
||||
show_main: "Open main window",
|
||||
no_provider_hint: " (No providers yet, please add them from the main window)",
|
||||
lightweight_mode: "Lightweight Mode",
|
||||
quit: "Quit",
|
||||
_auto_label: "Auto (Failover)",
|
||||
},
|
||||
@@ -31,12 +33,14 @@ impl TrayTexts {
|
||||
show_main: "メインウィンドウを開く",
|
||||
no_provider_hint:
|
||||
" (プロバイダーがまだありません。メイン画面から追加してください)",
|
||||
lightweight_mode: "軽量モード",
|
||||
quit: "終了",
|
||||
_auto_label: "自動 (フェイルオーバー)",
|
||||
},
|
||||
_ => Self {
|
||||
show_main: "打开主界面",
|
||||
no_provider_hint: " (无供应商,请在主界面添加)",
|
||||
lightweight_mode: "轻量模式",
|
||||
quit: "退出",
|
||||
_auto_label: "自动 (故障转移)",
|
||||
},
|
||||
@@ -382,6 +386,18 @@ pub fn create_tray_menu(
|
||||
menu_builder = menu_builder.separator();
|
||||
}
|
||||
|
||||
let lightweight_item = CheckMenuItem::with_id(
|
||||
app,
|
||||
"lightweight_mode",
|
||||
tray_texts.lightweight_mode,
|
||||
true,
|
||||
crate::lightweight::is_lightweight_mode(),
|
||||
None::<&str>,
|
||||
)
|
||||
.map_err(|e| AppError::Message(format!("创建轻量模式菜单失败: {e}")))?;
|
||||
|
||||
menu_builder = menu_builder.item(&lightweight_item).separator();
|
||||
|
||||
// 退出菜单(分隔符已在上面的 section 循环中添加)
|
||||
let quit_item = MenuItem::with_id(app, "quit", tray_texts.quit, true, None::<&str>)
|
||||
.map_err(|e| AppError::Message(format!("创建退出菜单失败: {e}")))?;
|
||||
@@ -393,6 +409,20 @@ pub fn create_tray_menu(
|
||||
.map_err(|e| AppError::Message(format!("构建菜单失败: {e}")))
|
||||
}
|
||||
|
||||
pub fn refresh_tray_menu(app: &tauri::AppHandle) {
|
||||
use crate::store::AppState;
|
||||
|
||||
if let Some(state) = app.try_state::<AppState>() {
|
||||
if let Ok(new_menu) = create_tray_menu(app, state.inner()) {
|
||||
if let Some(tray) = app.tray_by_id("main") {
|
||||
if let Err(e) = tray.set_menu(Some(new_menu)) {
|
||||
log::error!("刷新托盘菜单失败: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn apply_tray_policy(app: &tauri::AppHandle, dock_visible: bool) {
|
||||
use tauri::ActivationPolicy;
|
||||
@@ -430,6 +460,19 @@ pub fn handle_tray_menu_event(app: &tauri::AppHandle, event_id: &str) {
|
||||
{
|
||||
apply_tray_policy(app, true);
|
||||
}
|
||||
} else if crate::lightweight::is_lightweight_mode() {
|
||||
if let Err(e) = crate::lightweight::exit_lightweight_mode(app) {
|
||||
log::error!("退出轻量模式重建窗口失败: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
"lightweight_mode" => {
|
||||
if crate::lightweight::is_lightweight_mode() {
|
||||
if let Err(e) = crate::lightweight::exit_lightweight_mode(app) {
|
||||
log::error!("退出轻量模式失败: {e}");
|
||||
}
|
||||
} else if let Err(e) = crate::lightweight::enter_lightweight_mode(app) {
|
||||
log::error!("进入轻量模式失败: {e}");
|
||||
}
|
||||
}
|
||||
"quit" => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "CC Switch",
|
||||
"version": "3.12.1",
|
||||
"version": "3.12.3",
|
||||
"identifier": "com.ccswitch.desktop",
|
||||
"build": {
|
||||
"frontendDist": "../dist",
|
||||
@@ -26,7 +26,7 @@
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": "default-src 'self'; img-src 'self' data:; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self' ipc: http://ipc.localhost https: http:",
|
||||
"csp": "default-src 'self'; img-src 'self' data: https: http:; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self' ipc: http://ipc.localhost https: http:",
|
||||
"assetProtocol": {
|
||||
"enable": true,
|
||||
"scope": []
|
||||
@@ -50,7 +50,7 @@
|
||||
}
|
||||
},
|
||||
"macOS": {
|
||||
"minimumSystemVersion": "10.15"
|
||||
"minimumSystemVersion": "12.0"
|
||||
}
|
||||
},
|
||||
"plugins": {
|
||||
|
||||
@@ -10,7 +10,9 @@ use cc_switch_lib::{
|
||||
|
||||
#[path = "support.rs"]
|
||||
mod support;
|
||||
use support::{create_test_state_with_config, ensure_test_home, reset_test_fs, test_mutex};
|
||||
use support::{
|
||||
create_test_state, create_test_state_with_config, ensure_test_home, reset_test_fs, test_mutex,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn import_default_config_claude_persists_provider() {
|
||||
@@ -560,3 +562,96 @@ fn enabling_claude_mcp_skips_when_claude_config_absent() {
|
||||
"~/.claude.json should still not exist after skipped sync"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sync_all_enabled_removes_known_disabled_but_preserves_unknown_live_entries() {
|
||||
let _guard = test_mutex().lock().expect("acquire test mutex");
|
||||
reset_test_fs();
|
||||
let _home = ensure_test_home();
|
||||
|
||||
let mcp_path = get_claude_mcp_path();
|
||||
fs::write(
|
||||
&mcp_path,
|
||||
serde_json::to_string_pretty(&json!({
|
||||
"mcpServers": {
|
||||
"managed-disabled": {
|
||||
"type": "stdio",
|
||||
"command": "echo"
|
||||
},
|
||||
"external-only": {
|
||||
"type": "stdio",
|
||||
"command": "external"
|
||||
}
|
||||
}
|
||||
}))
|
||||
.expect("serialize claude mcp"),
|
||||
)
|
||||
.expect("seed claude mcp");
|
||||
|
||||
let state = create_test_state().expect("create test state");
|
||||
|
||||
state
|
||||
.db
|
||||
.save_mcp_server(&McpServer {
|
||||
id: "managed-disabled".to_string(),
|
||||
name: "Managed Disabled".to_string(),
|
||||
server: json!({
|
||||
"type": "stdio",
|
||||
"command": "echo"
|
||||
}),
|
||||
apps: McpApps {
|
||||
claude: false,
|
||||
codex: false,
|
||||
gemini: false,
|
||||
opencode: false,
|
||||
},
|
||||
description: None,
|
||||
homepage: None,
|
||||
docs: None,
|
||||
tags: Vec::new(),
|
||||
})
|
||||
.expect("save disabled server");
|
||||
state
|
||||
.db
|
||||
.save_mcp_server(&McpServer {
|
||||
id: "managed-enabled".to_string(),
|
||||
name: "Managed Enabled".to_string(),
|
||||
server: json!({
|
||||
"type": "stdio",
|
||||
"command": "managed"
|
||||
}),
|
||||
apps: McpApps {
|
||||
claude: true,
|
||||
codex: false,
|
||||
gemini: false,
|
||||
opencode: false,
|
||||
},
|
||||
description: None,
|
||||
homepage: None,
|
||||
docs: None,
|
||||
tags: Vec::new(),
|
||||
})
|
||||
.expect("save enabled server");
|
||||
|
||||
McpService::sync_all_enabled(&state).expect("reconcile mcp");
|
||||
|
||||
let text = fs::read_to_string(&mcp_path).expect("read claude mcp");
|
||||
let value: serde_json::Value = serde_json::from_str(&text).expect("parse claude mcp");
|
||||
let servers = value
|
||||
.get("mcpServers")
|
||||
.and_then(|entry| entry.as_object())
|
||||
.expect("mcpServers object");
|
||||
|
||||
assert!(
|
||||
!servers.contains_key("managed-disabled"),
|
||||
"DB-known disabled server should be removed from live config"
|
||||
);
|
||||
assert!(
|
||||
servers.contains_key("managed-enabled"),
|
||||
"DB-known enabled server should be present in live config"
|
||||
);
|
||||
assert!(
|
||||
servers.contains_key("external-only"),
|
||||
"live entries unknown to DB should be preserved"
|
||||
);
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user