8 Commits

Author SHA1 Message Date
e76f0fefb4 更新版本
Some checks failed
Build Linux / Build Linux x86_64 (push) Has been cancelled
Build Test / Build Test (Linux) (push) Has been cancelled
Build Test / Build Test (Windows) (push) Has been cancelled
Build Test / Build Test (macOS) (push) Has been cancelled
Build Test / Build Test Summary (push) Has been cancelled
2025-09-28 11:03:09 +08:00
e3e35ff3b3 调整节点 2025-09-28 11:02:49 +08:00
2d5d230ff8 调整节点 2025-09-27 22:05:32 +08:00
564c9d77f6 修复导航栏claude版本不显示
Some checks failed
Build Linux / Build Linux x86_64 (push) Has been cancelled
Build Test / Build Test (Linux) (push) Has been cancelled
Build Test / Build Test (Windows) (push) Has been cancelled
Build Test / Build Test (macOS) (push) Has been cancelled
Build Test / Build Test Summary (push) Has been cancelled
2025-09-16 17:14:05 +08:00
4cdb22788f 修改面板大小
Some checks failed
Build Linux / Build Linux x86_64 (push) Has been cancelled
Build Test / Build Test (Linux) (push) Has been cancelled
Build Test / Build Test (Windows) (push) Has been cancelled
Build Test / Build Test (macOS) (push) Has been cancelled
Build for Open Source / build (Linux, ubuntu-22.04, ) (push) Has been cancelled
Build for Open Source / build (Windows, windows-latest, ) (push) Has been cancelled
Build for Open Source / build (macOS, macos-latest, ) (push) Has been cancelled
Release / build-linux (push) Has been cancelled
Release / build-macos (push) Has been cancelled
Build Test / Build Test Summary (push) Has been cancelled
Release / Create Release (push) Has been cancelled
2025-09-11 00:18:11 +08:00
3456f9e06d 修复packycode无法测速以及更新滴滴车地址 2025-09-10 23:16:59 +08:00
564d7a29fb 修复打包后CCR扫描不到 2025-09-08 09:39:45 +08:00
77837d3656 修复windows编译错误 2025-09-08 08:50:09 +08:00
19 changed files with 1554 additions and 356 deletions

192
.github/workflows/README.md vendored Normal file
View File

@@ -0,0 +1,192 @@
# GitHub Actions 工作流说明
本项目包含多个 GitHub Actions 工作流,适用于不同的使用场景。
## 📋 工作流列表
### 1. `build-opensource.yml` - 开源发布(推荐)
**用途**:正式版本发布,适合开源项目分发
**触发条件**
- 创建版本标签 (`v*`)
- 手动触发
**特点**
- ✅ 无需代码签名
- ✅ 自动创建 GitHub Release
- ✅ 支持所有平台
- ✅ 生成用户友好的安装包
**使用方法**
```bash
# 创建版本发布
git tag v1.0.0
git push origin v1.0.0
```
---
### 2. `dev-ci.yml` - 开发测试
**用途**PR 和开发分支的自动化测试
**触发条件**
- Push 到 `dev`, `develop`, `feature/*` 分支
- 创建 PR 到 `main``dev`
**特点**
- ✅ 代码格式检查
- ✅ Clippy 静态分析
- ✅ TypeScript 类型检查
- ✅ 单元测试
- ✅ 构建验证
**检查项目**
- Rust 格式化 (`cargo fmt`)
- Rust 代码质量 (`cargo clippy`)
- TypeScript 类型 (`tsc`)
- 测试运行 (`cargo test`)
---
### 3. `quick-build.yml` - 快速构建
**用途**:快速测试构建,不创建发布
**触发条件**
- 仅手动触发
**特点**
- ✅ 可选择特定平台
- ✅ 最小化配置
- ✅ 快速构建
- ✅ 保存构建产物 7 天
**使用方法**
1. GitHub → Actions → Quick Build
2. 选择目标平台
3. 点击 Run workflow
---
### 4. `build.yml` - 完整构建(需要签名)
**用途**:需要代码签名的正式发布
**要求**
- ❗ 需要配置 Apple 证书
- ❗ 需要 GitHub Secrets
**不推荐用于**
- 开源项目
- 个人开发
- 没有 Apple 开发者账号的情况
---
### 5. `build-unsigned.yml` - 未签名构建
**用途**:不需要签名的完整构建
**特点**
- ✅ 支持所有平台
- ✅ 无需证书配置
- ⚠️ macOS 用户需要手动信任
---
## 🎯 推荐使用方案
### 开源项目
使用 **`build-opensource.yml`**
- 简单配置
- 自动发布
- 用户友好
### 日常开发
使用 **`dev-ci.yml`**
- 自动化测试
- 代码质量保证
- PR 检查
### 快速测试
使用 **`quick-build.yml`**
- 手动触发
- 选择平台
- 快速验证
## 🚀 快速开始
### 1. 首次设置
```bash
# 确保工作流文件存在
ls -la .github/workflows/
# 推送到 GitHub
git add .github/
git commit -m "添加 GitHub Actions 工作流"
git push origin main
```
### 2. 创建发布
```bash
# 更新版本号
# 编辑 src-tauri/Cargo.toml, src-tauri/tauri.conf.json, package.json
# 提交更改
git add .
git commit -m "chore: bump version to v1.0.0"
# 创建标签并推送
git tag v1.0.0
git push origin v1.0.0
# 工作流会自动运行并创建 Release Draft
```
### 3. 开发测试
```bash
# 创建功能分支
git checkout -b feature/new-feature
# 推送会自动触发测试
git push origin feature/new-feature
```
## 📝 注意事项
1. **开源项目不需要代码签名**
- 用户需要手动信任应用是正常的
- 这不影响应用的功能
2. **构建产物保留时间**
- Release: 永久保存
- Artifacts: 7 天后自动删除
3. **并行构建**
- 所有平台同时构建
- 一个平台失败不影响其他平台
## 🔧 故障排除
### 构建失败
1. 检查 Actions 日志
2. 确认依赖版本正确
3. 本地测试构建:`bun run tauri build`
### Linux 构建问题
确保安装所有依赖:
```bash
sudo apt-get update
sudo apt-get install -y \
libwebkit2gtk-4.1-dev \
libgtk-3-dev \
libayatana-appindicator3-dev \
librsvg2-dev
```
### Windows 构建问题
- 确保使用 Windows Server 2019 或更高版本
- 检查 Visual Studio Build Tools
## 📚 相关文档
- [Tauri 构建文档](https://tauri.app/v1/guides/building/)
- [GitHub Actions 文档](https://docs.github.com/en/actions)
- [项目 README](../../README.md)

View File

@@ -17,14 +17,14 @@ jobs:
# github.event.pull_request.user.login == 'external-contributor' ||
# github.event.pull_request.user.login == 'new-developer' ||
# github.event.pull_request.author_association == 'FIRST_TIME_CONTRIBUTOR'
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: read
issues: read
id-token: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
@@ -36,10 +36,10 @@ jobs:
uses: anthropics/claude-code-action@beta
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
# Optional: Specify model (defaults to Claude Sonnet 4, uncomment for Claude Opus 4)
# model: "claude-opus-4-20250514"
# Direct prompt for automated review (no @claude mention needed)
direct_prompt: |
Please review this pull request and provide feedback on:
@@ -50,24 +50,24 @@ jobs:
- Test coverage
Be constructive and helpful in your feedback.
# Optional: Customize review based on file types
# direct_prompt: |
# Review this PR focusing on:
# - For TypeScript files: Type safety and proper interface usage
# - For API endpoints: Security, input validation, and error handling
# - For React components: Performance, accessibility, and best practices
# - For tests: Coverage, edge cases, and test quality
# - For tests: Coverage, edge cases, and test.md quality
# Optional: Different prompts for different authors
# direct_prompt: |
# ${{ github.event.pull_request.author_association == 'FIRST_TIME_CONTRIBUTOR' &&
# ${{ github.event.pull_request.author_association == 'FIRST_TIME_CONTRIBUTOR' &&
# 'Welcome! Please review this PR from a first-time contributor. Be encouraging and provide detailed explanations for any suggestions.' ||
# 'Please provide a thorough code review focusing on our coding standards and best practices.' }}
# Optional: Add specific tools for running tests or linting
# allowed_tools: "Bash(npm run test),Bash(npm run lint),Bash(npm run typecheck)"
# allowed_tools: "Bash(npm run test.md),Bash(npm run lint),Bash(npm run typecheck)"
# Optional: Skip review for certain conditions
# if: |
# !contains(github.event.pull_request.title, '[skip-review]') &&

View File

@@ -34,26 +34,26 @@ jobs:
uses: anthropics/claude-code-action@beta
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
# Optional: Specify model (defaults to Claude Sonnet 4, uncomment for Claude Opus 4)
model: "claude-opus-4-20250514"
# Optional: Customize the trigger phrase (default: @claude)
# trigger_phrase: "/claude"
# Optional: Trigger when specific user is assigned to an issue
# assignee_trigger: "claude-bot"
# Optional: Allow Claude to run specific commands
# allowed_tools: "Bash(npm install),Bash(npm run build),Bash(npm run test:*),Bash(npm run lint:*)"
# allowed_tools: "Bash(npm install),Bash(npm run build),Bash(npm run test.md:*),Bash(npm run lint:*)"
# Optional: Add custom instructions for Claude to customize its behavior for your project
# custom_instructions: |
# Follow our coding standards
# Ensure all new code has tests
# Use TypeScript for new files
# Optional: Custom environment variables for Claude
# claude_env: |
# NODE_ENV: test
# NODE_ENV: test.md

View File

@@ -1,7 +1,7 @@
{
"name": "claudia",
"private": true,
"version": "1.2.0",
"version": "1.2.2",
"license": "AGPL-3.0",
"type": "module",
"scripts": {

View File

@@ -1,6 +1,6 @@
[package]
name = "claudia"
version = "1.2.0"
version = "1.2.2"
description = "GUI app and Toolkit for Claude Code"
authors = ["mufeedvh", "123vviekr"]
license = "AGPL-3.0"

View File

@@ -7,7 +7,7 @@
<key>LSMinimumSystemVersion</key>
<string>10.15</string>
<key>CFBundleShortVersionString</key>
<string>0.1.0</string>
<string>1.2.0</string>
<key>CFBundleName</key>
<string>Claudia</string>
<key>CFBundleDisplayName</key>

View File

@@ -202,7 +202,16 @@ fn find_which_installations() -> Vec<ClaudeInstallation> {
let mut installations = Vec::new();
match Command::new(command_name).arg("claude").output() {
// Create command with enhanced PATH for production environments
let mut cmd = Command::new(command_name);
cmd.arg("claude");
// In production (DMG), we need to ensure proper PATH is set
let enhanced_path = build_enhanced_path();
debug!("Using enhanced PATH for {}: {}", command_name, enhanced_path);
cmd.env("PATH", enhanced_path);
match cmd.output() {
Ok(output) if output.status.success() => {
let output_str = String::from_utf8_lossy(&output.stdout).trim().to_string();
@@ -401,7 +410,11 @@ fn find_standard_installations() -> Vec<ClaudeInstallation> {
}
// Also check if claude is available in PATH (without full path)
if let Ok(output) = Command::new("claude").arg("--version").output() {
let mut path_cmd = Command::new("claude");
path_cmd.arg("--version");
path_cmd.env("PATH", build_enhanced_path());
if let Ok(output) = path_cmd.output() {
if output.status.success() {
debug!("claude is available in PATH");
// Combine stdout and stderr for robust version extraction
@@ -427,7 +440,11 @@ fn find_standard_installations() -> Vec<ClaudeInstallation> {
/// Get Claude version by running --version command
fn get_claude_version(path: &str) -> Result<Option<String>, String> {
match Command::new(path).arg("--version").output() {
// Use the helper function to create command with proper environment
let mut cmd = create_command_with_env(path);
cmd.arg("--version");
match cmd.output() {
Ok(output) => {
if output.status.success() {
// Combine stdout and stderr for robust version extraction
@@ -556,11 +573,15 @@ pub fn create_command_with_env(program: &str) -> Command {
info!("Creating command for: {}", program);
// Build enhanced PATH for production environments (DMG/App Bundle)
let enhanced_path = build_enhanced_path();
debug!("Enhanced PATH: {}", enhanced_path);
cmd.env("PATH", enhanced_path.clone());
// Inherit essential environment variables from parent process
for (key, value) in std::env::vars() {
// Pass through PATH and other essential environment variables
if key == "PATH"
|| key == "HOME"
// Pass through essential environment variables (excluding PATH which we set above)
if key == "HOME"
|| key == "USER"
|| key == "SHELL"
|| key == "LANG"
@@ -595,7 +616,12 @@ pub fn create_command_with_env(program: &str) -> Command {
if program.contains("/.nvm/versions/node/") {
if let Some(node_bin_dir) = std::path::Path::new(program).parent() {
// Ensure the Node.js bin directory is in PATH
let current_path = std::env::var("PATH").unwrap_or_default();
let current_path = cmd.get_envs()
.find(|(k, _)| k.to_str() == Some("PATH"))
.and_then(|(_, v)| v)
.and_then(|v| v.to_str())
.unwrap_or(&enhanced_path)
.to_string();
let node_bin_str = node_bin_dir.to_string_lossy();
if !current_path.contains(&node_bin_str.as_ref()) {
let new_path = format!("{}:{}", node_bin_str, current_path);
@@ -607,3 +633,73 @@ pub fn create_command_with_env(program: &str) -> Command {
cmd
}
/// Build an enhanced PATH that includes all possible Claude installation locations
/// This is especially important for DMG/packaged applications where PATH may be limited
fn build_enhanced_path() -> String {
let mut paths = Vec::new();
// Start with current PATH
if let Ok(current_path) = std::env::var("PATH") {
paths.push(current_path);
}
// Add standard system paths that might be missing in packaged apps
let system_paths = vec![
"/usr/local/bin",
"/usr/bin",
"/bin",
"/opt/homebrew/bin",
"/opt/homebrew/sbin",
];
for path in system_paths {
if PathBuf::from(path).exists() {
paths.push(path.to_string());
}
}
// Add user-specific paths
if let Ok(home) = std::env::var("HOME") {
let user_paths = vec![
format!("{}/.local/bin", home),
format!("{}/.claude/local", home),
format!("{}/.npm-global/bin", home),
format!("{}/.yarn/bin", home),
format!("{}/.bun/bin", home),
format!("{}/bin", home),
format!("{}/.config/yarn/global/node_modules/.bin", home),
format!("{}/node_modules/.bin", home),
];
for path in user_paths {
if PathBuf::from(&path).exists() {
paths.push(path);
}
}
// Add all NVM node versions
let nvm_dir = PathBuf::from(&home).join(".nvm/versions/node");
if nvm_dir.exists() {
if let Ok(entries) = std::fs::read_dir(&nvm_dir) {
for entry in entries.flatten() {
if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
let bin_path = entry.path().join("bin");
if bin_path.exists() {
paths.push(bin_path.to_string_lossy().to_string());
}
}
}
}
}
}
// Remove duplicates while preserving order
let mut seen = std::collections::HashSet::new();
let unique_paths: Vec<String> = paths
.into_iter()
.filter(|path| seen.insert(path.clone()))
.collect();
unique_paths.join(":")
}

View File

@@ -26,9 +26,30 @@ pub struct CcrServiceInfo {
pub message: String,
}
/// 获取候选可执行名
fn candidate_binaries() -> Vec<&'static str> {
// 覆盖常见发布名与别名
vec![
"ccr",
"claude-code-router",
// Windows 扩展
"ccr.exe",
"ccr.cmd",
"claude-code-router.exe",
"claude-code-router.cmd",
// Node 安装中的可能文件名
"ccr.js",
"ccr.mjs",
"claude-code-router.js",
"claude-code-router.mjs",
]
}
/// 获取可能的 CCR 路径列表
fn get_possible_ccr_paths() -> Vec<String> {
let mut paths = vec!["ccr".to_string()]; // PATH 中的 ccr
let mut paths: Vec<String> = Vec::new();
// PATH 中的候选名(稍后用 PATH 遍历拼接,这里仅保留可直接执行名)
paths.extend(candidate_binaries().into_iter().map(|s| s.to_string()));
// 获取用户主目录
let home = std::env::var("HOME").or_else(|_| std::env::var("USERPROFILE")).unwrap_or_default();
@@ -36,13 +57,25 @@ fn get_possible_ccr_paths() -> Vec<String> {
#[cfg(target_os = "macos")]
{
// macOS 特定路径
paths.extend(vec![
"/usr/local/bin/ccr".to_string(),
"/opt/homebrew/bin/ccr".to_string(),
format!("{}/.nvm/versions/node/*/bin/ccr", home), // 通配符路径需要特殊处理
"/usr/local/lib/node_modules/.bin/ccr".to_string(),
"/opt/homebrew/lib/node_modules/.bin/ccr".to_string(),
]);
// 常见全局 bin 目录
for bin in ["ccr", "claude-code-router"] {
paths.push(format!("/usr/local/bin/{}", bin));
paths.push(format!("/opt/homebrew/bin/{}", bin));
}
// NVM 全局安装的二进制(通配)
for bin in ["ccr", "claude-code-router"] {
paths.push(format!("{}/.nvm/versions/node/*/bin/{}", home, bin));
}
// 全局 node_modules/.bin
for bin in ["ccr", "claude-code-router"] {
paths.push(format!("/usr/local/lib/node_modules/.bin/{}", bin));
paths.push(format!("/opt/homebrew/lib/node_modules/.bin/{}", bin));
}
// 添加常见的 Node.js 版本路径
for version in &["v16", "v18", "v20", "v21", "v22"] {
paths.push(format!("{}/.nvm/versions/node/{}.*/bin/ccr", home, version));
}
}
#[cfg(target_os = "windows")]
@@ -52,35 +85,201 @@ fn get_possible_ccr_paths() -> Vec<String> {
let program_files_x86 = std::env::var("ProgramFiles(x86)").unwrap_or_else(|_| "C:\\Program Files (x86)".to_string());
let appdata = std::env::var("APPDATA").unwrap_or_else(|_| format!("{}\\AppData\\Roaming", home));
paths.extend(vec![
"ccr.exe".to_string(),
"ccr.cmd".to_string(),
format!("{}\\npm\\ccr.cmd", appdata),
format!("{}\\npm\\ccr.exe", appdata),
format!("{}\\nodejs\\ccr.cmd", program_files),
format!("{}\\nodejs\\ccr.exe", program_files),
format!("{}\\nodejs\\ccr.cmd", program_files_x86),
format!("{}\\nodejs\\ccr.exe", program_files_x86),
format!("{}\\AppData\\Roaming\\npm\\ccr.cmd", home),
format!("{}\\AppData\\Roaming\\npm\\ccr.exe", home),
]);
for bin in [
"ccr.exe", "ccr.cmd", "claude-code-router.exe", "claude-code-router.cmd",
] {
paths.push(bin.to_string());
paths.push(format!("{}\\npm\\{}", appdata, bin));
paths.push(format!("{}\\nodejs\\{}", program_files, bin));
paths.push(format!("{}\\nodejs\\{}", program_files_x86, bin));
paths.push(format!("{}\\AppData\\Roaming\\npm\\{}", home, bin));
}
}
#[cfg(target_os = "linux")]
{
// Linux 特定路径
paths.extend(vec![
"/usr/bin/ccr".to_string(),
"/usr/local/bin/ccr".to_string(),
format!("{}/.local/bin/ccr", home),
format!("{}/.npm-global/bin/ccr", home),
"/usr/lib/node_modules/.bin/ccr".to_string(),
]);
for bin in ["ccr", "claude-code-router"] {
paths.push(format!("/usr/bin/{}", bin));
paths.push(format!("/usr/local/bin/{}", bin));
paths.push(format!("{}/.local/bin/{}", home, bin));
paths.push(format!("{}/.npm-global/bin/{}", home, bin));
paths.push(format!("/usr/lib/node_modules/.bin/{}", bin));
}
}
paths
}
/// 获取扩展的 PATH 环境变量
fn get_extended_path() -> String {
let mut extended_path = std::env::var("PATH").unwrap_or_default();
let separator = if cfg!(target_os = "windows") { ";" } else { ":" };
// 添加常见的额外路径
let additional_paths = if cfg!(target_os = "macos") {
vec![
"/usr/local/bin",
"/opt/homebrew/bin",
"/opt/homebrew/sbin",
// Node.js 相关路径
"/usr/local/lib/node_modules/.bin",
"/opt/homebrew/lib/node_modules/.bin",
]
} else if cfg!(target_os = "windows") {
vec![]
} else {
vec![
"/usr/local/bin",
"/opt/bin",
]
};
// 添加用户特定路径
if let Ok(home) = std::env::var("HOME") {
let user_paths = if cfg!(target_os = "macos") {
// 动态发现 Node 版本管理工具的 bin 目录
let mut list = vec![
format!("{}/.local/bin", home),
format!("{}/.cargo/bin", home),
];
// nvm: ~/.nvm/versions/node/*/bin
let nvm_versions_root = format!("{}/.nvm/versions/node", home);
if let Ok(entries) = std::fs::read_dir(&nvm_versions_root) {
for entry in entries.flatten() {
let p = entry.path().join("bin");
if p.exists() {
if let Some(s) = p.to_str() { list.push(s.to_string()); }
}
}
}
// volta
list.push(format!("{}/.volta/bin", home));
// asdf
let asdf_installs = format!("{}/.asdf/installs/nodejs", home);
if let Ok(entries) = std::fs::read_dir(&asdf_installs) {
for entry in entries.flatten() {
let p = entry.path().join("bin");
if p.exists() {
if let Some(s) = p.to_str() { list.push(s.to_string()); }
}
}
}
list.push(format!("{}/.asdf/shims", home));
// fnm
let fnm_versions = format!("{}/.fnm/node-versions", home);
if let Ok(entries) = std::fs::read_dir(&fnm_versions) {
for entry in entries.flatten() {
let p = entry.path().join("installation").join("bin");
if p.exists() {
if let Some(s) = p.to_str() { list.push(s.to_string()); }
}
}
}
list
} else if cfg!(target_os = "windows") {
if let Ok(appdata) = std::env::var("APPDATA") {
vec![
format!("{}\\npm", appdata),
]
} else {
vec![]
}
} else {
vec![
format!("{}/.local/bin", home),
format!("{}/.npm-global/bin", home),
]
};
for path in user_paths {
if std::path::Path::new(&path).exists() && !extended_path.contains(&path) {
extended_path.push_str(separator);
extended_path.push_str(&path);
}
}
}
// 添加系统额外路径
for path in additional_paths {
if std::path::Path::new(path).exists() && !extended_path.contains(path) {
extended_path.push_str(separator);
extended_path.push_str(path);
}
}
extended_path
}
/// 通过 shell 查找 CCR
fn find_ccr_via_shell() -> Option<String> {
// 尝试通过 shell 获取 ccr 路径
let shell_cmd = if cfg!(target_os = "windows") {
"where ccr claude-code-router"
} else {
"command -v ccr || which ccr || command -v claude-code-router || which claude-code-router"
};
let shell = if cfg!(target_os = "windows") {
"cmd"
} else {
"sh"
};
let shell_args = if cfg!(target_os = "windows") {
vec!["/C", shell_cmd]
} else {
vec!["-c", shell_cmd]
};
if let Ok(output) = Command::new(shell)
.args(&shell_args)
.env("PATH", get_extended_path())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output() {
if output.status.success() {
let path = String::from_utf8_lossy(&output.stdout).lines().next().unwrap_or("").trim().to_string();
if !path.is_empty() && test_ccr_command(&path) {
info!("Found ccr via shell: {}", path);
return Some(path);
}
}
}
// 如果标准方法失败,尝试加载用户的 shell 配置
if !cfg!(target_os = "windows") {
let home = std::env::var("HOME").ok()?;
let shell_configs = vec![
format!("{}/.bashrc", home),
format!("{}/.zshrc", home),
format!("{}/.profile", home),
];
for config in shell_configs {
if std::path::Path::new(&config).exists() {
let cmd = format!("source {} && (command -v ccr || command -v claude-code-router)", config);
if let Ok(output) = Command::new("sh")
.args(&["-c", &cmd])
.env("PATH", get_extended_path())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output() {
if output.status.success() {
let path = String::from_utf8_lossy(&output.stdout).lines().next().unwrap_or("").trim().to_string();
if !path.is_empty() && test_ccr_command(&path) {
info!("Found ccr via shell config {}: {}", config, path);
return Some(path);
}
}
}
}
}
}
None
}
/// 查找实际的 CCR 路径
fn find_ccr_path() -> Option<String> {
// 先检查缓存
@@ -90,6 +289,97 @@ fn find_ccr_path() -> Option<String> {
}
}
// 硬编码检查最常见的路径(针对打包应用的特殊处理)
let home = std::env::var("HOME").unwrap_or_default();
let mut hardcoded_paths: Vec<String> = Vec::new();
for bin in ["ccr", "claude-code-router"] {
hardcoded_paths.push(format!("/usr/local/bin/{}", bin));
hardcoded_paths.push(format!("/opt/homebrew/bin/{}", bin));
}
// 动态添加 NVM 路径
let nvm_base = format!("{}/.nvm/versions/node", home);
if std::path::Path::new(&nvm_base).exists() {
if let Ok(entries) = std::fs::read_dir(&nvm_base) {
for entry in entries.flatten() {
if let Ok(name) = entry.file_name().into_string() {
if name.starts_with('v') {
for bin in ["ccr", "claude-code-router"] {
let ccr_path = format!("{}/{}/bin/{}", nvm_base, name, bin);
hardcoded_paths.push(ccr_path);
}
}
}
}
}
}
info!("Checking hardcoded paths: {:?}", hardcoded_paths);
for path in &hardcoded_paths {
if std::path::Path::new(path).exists() {
// 对于打包应用,存在即认为可用,不进行执行测试
info!("Found ccr at hardcoded path: {}", path);
if let Ok(mut cached) = CCR_PATH.lock() {
*cached = Some(path.to_string());
}
return Some(path.to_string());
}
}
// 获取扩展的 PATH
let extended_path = get_extended_path();
// 首先尝试通过 shell 查找(最可靠)
if let Some(path) = find_ccr_via_shell() {
if let Ok(mut cached) = CCR_PATH.lock() {
*cached = Some(path.clone());
}
return Some(path);
}
// 然后尝试使用带有扩展 PATH 的 which/command -v 命令
for name in ["ccr", "claude-code-router"] {
if let Ok(output) = Command::new("sh")
.env("PATH", &extended_path)
.arg("-c")
.arg(format!("command -v {} || which {}", name, name))
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output() {
if output.status.success() {
let path = String::from_utf8_lossy(&output.stdout).lines().next().unwrap_or("").trim().to_string();
if !path.is_empty() && test_ccr_command(&path) {
info!("Found {} using shell which: {}", name, path);
if let Ok(mut cached) = CCR_PATH.lock() {
*cached = Some(path.clone());
}
return Some(path);
}
}
}
}
// 然后检查扩展后的 PATH
let separator = if cfg!(target_os = "windows") { ";" } else { ":" };
for path_dir in extended_path.split(separator) {
for name in candidate_binaries() {
let candidate = if cfg!(target_os = "windows") {
format!("{}\\{}", path_dir, name)
} else {
format!("{}/{}", path_dir, name)
};
if test_ccr_command(&candidate) {
info!("Found CCR in PATH: {}", candidate);
if let Ok(mut cached) = CCR_PATH.lock() {
*cached = Some(candidate.clone());
}
return Some(candidate);
}
}
}
// 最后尝试预定义的路径列表
let possible_paths = get_possible_ccr_paths();
for path in &possible_paths {
@@ -119,23 +409,102 @@ fn find_ccr_path() -> Option<String> {
}
}
error!("CCR not found in any location. Original PATH: {:?}", std::env::var("PATH"));
error!("Extended PATH: {}", extended_path);
error!("Searched paths: {:?}", possible_paths);
None
}
/// 测试给定路径的 CCR 命令是否可用
fn test_ccr_command(path: &str) -> bool {
let output = Command::new(path)
.arg("version")
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output();
// 首先检查文件是否存在
let path_obj = std::path::Path::new(path);
if !path_obj.exists() {
debug!("CCR path does not exist: {}", path);
return false;
}
matches!(output, Ok(result) if result.status.success())
// 如果是符号链接,解析真实路径
let real_path = if path_obj.is_symlink() {
match std::fs::read_link(path) {
Ok(target) => {
// 如果是相对路径,需要基于符号链接的目录来解析
if target.is_relative() {
if let Some(parent) = path_obj.parent() {
parent.join(target).to_string_lossy().to_string()
} else {
target.to_string_lossy().to_string()
}
} else {
target.to_string_lossy().to_string()
}
}
Err(e) => {
debug!("Failed to read symlink {}: {}", path, e);
return false;
}
}
} else {
path.to_string()
};
debug!("Testing CCR command at: {} (real path: {})", path, real_path);
// 如果是 .js 文件,使用 node 来执行
if real_path.ends_with(".js") {
let output = Command::new("node")
.arg(&real_path)
.arg("version")
.env("PATH", get_extended_path())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output();
match output {
Ok(result) => {
let success = result.status.success();
if !success {
let stderr = String::from_utf8_lossy(&result.stderr);
debug!("CCR command (via node) failed at {}: {}", real_path, stderr);
}
success
}
Err(e) => {
debug!("Failed to execute CCR via node at {}: {}", real_path, e);
false
}
}
} else {
// 直接执行,尝试多种版本参数
for arg in ["version", "-v", "--version"] {
let output = Command::new(path)
.arg(arg)
.env("PATH", get_extended_path())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output();
match output {
Ok(result) => {
if result.status.success() {
return true;
}
}
Err(_) => {
// 尝试下一个参数
}
}
}
debug!("CCR command did not respond to version flags at {}", path);
false
}
}
/// 检查 CCR 是否已安装
#[tauri::command]
pub async fn check_ccr_installation() -> Result<bool, String> {
Ok(find_ccr_path().is_some())
let path = find_ccr_path();
info!("CCR installation check result: {:?}", path);
Ok(path.is_some())
}
/// 获取 CCR 版本信息
@@ -147,11 +516,22 @@ pub async fn get_ccr_version() -> Result<String, String> {
let version_args = vec!["--version", "-v", "version"];
for arg in version_args {
let output = Command::new(&ccr_path)
.arg(arg)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output();
let output = if ccr_path.contains("node_modules") || ccr_path.contains(".nvm") {
Command::new("sh")
.arg("-c")
.arg(format!("{} {}", ccr_path, arg))
.env("PATH", get_extended_path())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()
} else {
Command::new(&ccr_path)
.arg(arg)
.env("PATH", get_extended_path())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()
};
if let Ok(result) = output {
if result.status.success() {
@@ -175,6 +555,114 @@ pub async fn get_ccr_service_status() -> Result<CcrServiceStatus, String> {
if !has_ccr_binary {
info!("CCR binary not found in PATH");
let original_path = std::env::var("PATH").unwrap_or_else(|_| "PATH not found".to_string());
let extended_path = get_extended_path();
// 动态扫描多个 Node 版本管理器目录以进行诊断
let home = std::env::var("HOME").unwrap_or_default();
let mut scan_dirs: Vec<String> = Vec::new();
// nvm
let nvm_versions_root = format!("{}/.nvm/versions/node", home);
if let Ok(entries) = std::fs::read_dir(&nvm_versions_root) {
for entry in entries.flatten() {
let p = entry.path().join("bin");
if p.exists() {
if let Some(s) = p.to_str() { scan_dirs.push(s.to_string()); }
}
}
}
// volta
scan_dirs.push(format!("{}/.volta/bin", home));
// asdf
scan_dirs.push(format!("{}/.asdf/shims", home));
let asdf_installs = format!("{}/.asdf/installs/nodejs", home);
if let Ok(entries) = std::fs::read_dir(&asdf_installs) {
for entry in entries.flatten() {
let p = entry.path().join("bin");
if p.exists() {
if let Some(s) = p.to_str() { scan_dirs.push(s.to_string()); }
}
}
}
// fnm
let fnm_versions = format!("{}/.fnm/node-versions", home);
if let Ok(entries) = std::fs::read_dir(&fnm_versions) {
for entry in entries.flatten() {
let p = entry.path().join("installation").join("bin");
if p.exists() {
if let Some(s) = p.to_str() { scan_dirs.push(s.to_string()); }
}
}
}
// 查找候选可执行
let mut found_candidates: Vec<String> = Vec::new();
for dir in &scan_dirs {
for name in ["ccr", "claude-code-router"] {
let p = format!("{}/{}", dir, name);
if std::path::Path::new(&p).exists() {
found_candidates.push(p);
}
}
}
// 直接尝试第一个候选
let direct_test = if let Some(first) = found_candidates.first() {
match Command::new(first)
.arg("-v")
.env("PATH", get_extended_path())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output() {
Ok(output) => {
if output.status.success() {
let version = String::from_utf8_lossy(&output.stdout);
format!("Direct execution SUCCESS: {}", version.trim())
} else {
let stderr = String::from_utf8_lossy(&output.stderr);
format!("Direct execution FAILED: {}", stderr.trim())
}
}
Err(e) => format!("Direct execution ERROR: {}", e)
}
} else {
"No candidate binary found in Node manager dirs".to_string()
};
// 为诊断展示每个扫描目录里的相关二进制
let mut scan_summary: Vec<String> = Vec::new();
for dir in &scan_dirs {
if std::path::Path::new(dir).exists() {
match std::fs::read_dir(dir) {
Ok(entries) => {
let files: Vec<String> = entries
.filter_map(|e| e.ok())
.filter_map(|e| e.file_name().to_str().map(|s| s.to_string()))
.filter(|name| name.contains("ccr") || name.contains("claude-code-router"))
.collect();
if !files.is_empty() {
scan_summary.push(format!("{} -> {:?}", dir, files));
}
}
Err(_) => {}
}
}
}
let debug_info = format!(
"CCR not found.\n\
Original PATH: {}\n\
Extended PATH: {}\n\
Candidates in Node manager dirs: {:?}\n\
Direct test: {}\n\
Scan details: {}",
original_path,
extended_path,
found_candidates,
direct_test,
scan_summary.join("; ")
);
return Ok(CcrServiceStatus {
is_running: false,
port: None,
@@ -182,7 +670,7 @@ pub async fn get_ccr_service_status() -> Result<CcrServiceStatus, String> {
has_ccr_binary: false,
ccr_version: None,
process_id: None,
raw_output: None,
raw_output: Some(debug_info),
});
}
@@ -193,19 +681,26 @@ pub async fn get_ccr_service_status() -> Result<CcrServiceStatus, String> {
// 获取 CCR 路径
let ccr_path = find_ccr_path().ok_or("CCR not found")?;
// 检查服务状态 - 设置环境变量和工作目录
let mut cmd = Command::new(&ccr_path);
cmd.arg("status")
.stdout(Stdio::piped())
.stderr(Stdio::piped());
// 检查服务状态
let mut cmd = if ccr_path.contains("node_modules") || ccr_path.contains(".nvm") {
// 如果是 Node.js 安装的路径,可能需要使用 node 来执行
let mut c = Command::new("sh");
c.arg("-c")
.arg(format!("{} status", ccr_path))
.env("PATH", get_extended_path())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
c
} else {
let mut c = Command::new(&ccr_path);
c.arg("status")
.env("PATH", get_extended_path())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
c
};
// 继承环境变量
cmd.env_clear();
for (key, value) in std::env::vars() {
cmd.env(key, value);
}
info!("Executing ccr status command");
info!("Executing ccr status command at path: {}", ccr_path);
let output = cmd.output();
let output = match output {
@@ -386,6 +881,7 @@ pub async fn start_ccr_service() -> Result<CcrServiceInfo, String> {
// 启动服务
let _output = Command::new(&ccr_path)
.arg("start")
.env("PATH", get_extended_path())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
@@ -419,6 +915,7 @@ pub async fn stop_ccr_service() -> Result<CcrServiceInfo, String> {
let output = Command::new(&ccr_path)
.arg("stop")
.env("PATH", get_extended_path())
.output()
.map_err(|e| format!("Failed to stop ccr service: {}", e))?;
@@ -448,6 +945,7 @@ pub async fn restart_ccr_service() -> Result<CcrServiceInfo, String> {
let output = Command::new(&ccr_path)
.arg("restart")
.env("PATH", get_extended_path())
.output()
.map_err(|e| format!("Failed to restart ccr service: {}", e))?;
@@ -490,6 +988,7 @@ pub async fn open_ccr_ui() -> Result<String, String> {
// 执行 ccr ui 命令
let _output = Command::new(&ccr_path)
.arg("ui")
.env("PATH", get_extended_path())
.spawn()
.map_err(|e| format!("Failed to open ccr ui: {}", e))?;
@@ -507,4 +1006,4 @@ pub async fn get_ccr_config_path() -> Result<String, String> {
.join("config.json");
Ok(config_path.to_string_lossy().to_string())
}
}

View File

@@ -623,102 +623,40 @@ pub async fn get_system_prompt() -> Result<String, String> {
/// Checks if Claude Code is installed and gets its version
#[tauri::command]
pub async fn check_claude_version(app: AppHandle) -> Result<ClaudeVersionStatus, String> {
pub async fn check_claude_version(_app: AppHandle) -> Result<ClaudeVersionStatus, String> {
log::info!("Checking Claude Code version");
let claude_path = match find_claude_binary(&app) {
Ok(path) => path,
Err(e) => {
return Ok(ClaudeVersionStatus {
is_installed: false,
version: None,
output: e,
});
}
};
use log::debug;debug!("Claude path: {}", claude_path);
// In production builds, we can't check the version directly
#[cfg(not(debug_assertions))]
{
log::warn!("Cannot check claude version in production build");
// If we found a path (either stored or in common locations), assume it's installed
if claude_path != "claude" && PathBuf::from(&claude_path).exists() {
return Ok(ClaudeVersionStatus {
is_installed: true,
version: None,
output: "Claude binary found at: ".to_string() + &claude_path,
});
} else {
return Ok(ClaudeVersionStatus {
is_installed: false,
version: None,
output: "Cannot verify Claude installation in production build. Please ensure Claude Code is installed.".to_string(),
});
}
// Try to find Claude installations with versions
let installations = crate::claude_binary::discover_claude_installations();
if installations.is_empty() {
return Ok(ClaudeVersionStatus {
is_installed: false,
version: None,
output: "Claude Code not found. Please ensure it's installed.".to_string(),
});
}
#[cfg(debug_assertions)]
{
let output = std::process::Command::new(claude_path)
.arg("--version")
.output();
match output {
Ok(output) => {
let stdout = String::from_utf8_lossy(&output.stdout).to_string();
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
// Use regex to directly extract version pattern (e.g., "1.0.41")
let version_regex = regex::Regex::new(r"(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?(?:\+[a-zA-Z0-9.-]+)?)").ok();
// Combine stdout and stderr for version extraction (some tools write version to stderr)
let mut version_src = stdout.clone();
if !stderr.is_empty() {
version_src.push('\n');
version_src.push_str(&stderr);
}
let version = if let Some(regex) = version_regex {
regex
.captures(&version_src)
.and_then(|captures| captures.get(1))
.map(|m| m.as_str().to_string())
} else {
None
};
let full_output = if stderr.is_empty() {
stdout.clone()
} else {
format!("{}\n{}", stdout, stderr)
};
// Check if the output matches the expected format
// Expected format: "1.0.17 (Claude Code)" or similar
let is_valid =
stdout.contains("(Claude Code)")
|| stdout.contains("Claude Code")
|| stderr.contains("(Claude Code)")
|| stderr.contains("Claude Code");
Ok(ClaudeVersionStatus {
is_installed: is_valid && output.status.success(),
version,
output: full_output.trim().to_string(),
})
// Find the best installation (highest version or first found)
let best_installation = installations
.into_iter()
.max_by(|a, b| {
match (&a.version, &b.version) {
(Some(v1), Some(v2)) => v1.cmp(v2),
(Some(_), None) => std::cmp::Ordering::Greater,
(None, Some(_)) => std::cmp::Ordering::Less,
(None, None) => std::cmp::Ordering::Equal,
}
Err(e) => {
log::error!("Failed to run claude command: {}", e);
Ok(ClaudeVersionStatus {
is_installed: false,
version: None,
output: format!("Command not found: {}", e),
})
}
}
}
})
.unwrap(); // Safe because we checked is_empty() above
log::info!("Found Claude installation: {:?}", best_installation);
Ok(ClaudeVersionStatus {
is_installed: true,
version: best_installation.version,
output: format!("Claude binary found at: {}", best_installation.path),
})
}
/// Saves the CLAUDE.md system prompt file

View File

@@ -724,3 +724,75 @@ pub async fn mcp_save_project_config(
Ok("Project MCP configuration saved".to_string())
}
/// Export configuration for MCP server
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MCPExportConfig {
pub name: String,
pub transport: String,
pub command: Option<String>,
pub args: Vec<String>,
pub env: HashMap<String, String>,
pub url: Option<String>,
pub scope: String,
}
/// Export result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MCPExportResult {
pub servers: Vec<MCPExportConfig>,
pub format: String, // "single" or "multiple"
}
/// Exports all MCP servers configuration
#[tauri::command]
pub async fn mcp_export_servers(app: AppHandle) -> Result<MCPExportResult, String> {
info!("Exporting MCP servers configuration");
// Get all servers
let servers = mcp_list(app.clone()).await?;
if servers.is_empty() {
return Ok(MCPExportResult {
servers: vec![],
format: "multiple".to_string(),
});
}
// Get detailed information for each server
let mut export_configs = Vec::new();
for server in &servers {
match mcp_get(app.clone(), server.name.clone()).await {
Ok(detailed_server) => {
export_configs.push(MCPExportConfig {
name: detailed_server.name,
transport: detailed_server.transport,
command: detailed_server.command,
args: detailed_server.args,
env: detailed_server.env,
url: detailed_server.url,
scope: detailed_server.scope,
});
}
Err(e) => {
error!("Failed to get details for server {}: {}", server.name, e);
// Still include basic information
export_configs.push(MCPExportConfig {
name: server.name.clone(),
transport: server.transport.clone(),
command: server.command.clone(),
args: server.args.clone(),
env: server.env.clone(),
url: server.url.clone(),
scope: server.scope.clone(),
});
}
}
}
Ok(MCPExportResult {
format: if export_configs.len() == 1 { "single" } else { "multiple" }.to_string(),
servers: export_configs,
})
}

View File

@@ -36,78 +36,69 @@ pub struct NodeSpeedTestResult {
/// 获取所有 PackyCode 节点
pub fn get_all_nodes() -> Vec<PackycodeNode> {
vec![
// 直连节点
// 公交车节点 (Bus Service)
PackycodeNode {
name: "直连1".to_string(),
name: "公交车默认节点".to_string(),
url: "https://api.packycode.com".to_string(),
node_type: NodeType::Direct,
description: "默认直连节点".to_string(),
description: "默认公交车直连节点".to_string(),
response_time: None,
available: None,
},
PackycodeNode {
name: "直连2 (HK-CN2)".to_string(),
name: "公交车 HK-CN2".to_string(),
url: "https://api-hk-cn2.packycode.com".to_string(),
node_type: NodeType::Direct,
description: "香港 CN2 线路".to_string(),
description: "香港 CN2 线路(公交车)".to_string(),
response_time: None,
available: None,
},
PackycodeNode {
name: "直连3 (US-CMIN2)".to_string(),
url: "https://api-us-cmin2.packycode.com".to_string(),
name: "公交车 HK-G".to_string(),
url: "https://api-hk-g.packycode.com".to_string(),
node_type: NodeType::Direct,
description: "美国 CMIN2 线路".to_string(),
description: "香港 G 线路(公交车)".to_string(),
response_time: None,
available: None,
},
PackycodeNode {
name: "直连4 (US-4837)".to_string(),
url: "https://api-us-4837.packycode.com".to_string(),
node_type: NodeType::Direct,
description: "美国 4837 线路".to_string(),
response_time: None,
available: None,
},
// 备用节点
PackycodeNode {
name: "备用1 (US-CN2)".to_string(),
url: "https://api-us-cn2.packycode.com".to_string(),
node_type: NodeType::Backup,
description: "美国 CN2 备用线路".to_string(),
response_time: None,
available: None,
},
PackycodeNode {
name: "备用2 (CF-Pro)".to_string(),
name: "公交车 CF-Pro".to_string(),
url: "https://api-cf-pro.packycode.com".to_string(),
node_type: NodeType::Backup,
description: "CloudFlare Pro 备用线路".to_string(),
node_type: NodeType::Direct,
description: "CloudFlare Pro 线路(公交车)".to_string(),
response_time: None,
available: None,
},
// 紧急节点
// 滴滴车节点 (Taxi Service)
PackycodeNode {
name: "测试节点1".to_string(),
url: "https://api-test.packyme.com".to_string(),
node_type: NodeType::Emergency,
description: "测试节点(非紧急情况勿用)".to_string(),
name: "滴滴车默认节点".to_string(),
url: "https://share-api.packycode.com".to_string(),
node_type: NodeType::Direct,
description: "默认滴滴车直连节点".to_string(),
response_time: None,
available: None,
},
PackycodeNode {
name: "测试节点2".to_string(),
url: "https://api-test-custom.packycode.com".to_string(),
node_type: NodeType::Emergency,
description: "自定义测试节点(非紧急情况勿用".to_string(),
name: "滴滴车 HK-CN2".to_string(),
url: "https://share-api-hk-cn2.packycode.com".to_string(),
node_type: NodeType::Direct,
description: "香港 CN2 线路(滴滴车".to_string(),
response_time: None,
available: None,
},
PackycodeNode {
name: "测试节点3".to_string(),
url: "https://api-tmp-test.dzz.ai".to_string(),
node_type: NodeType::Emergency,
description: "临时测试节点(非紧急情况勿用".to_string(),
name: "滴滴车 HK-G".to_string(),
url: "https://share-api-hk-g.packycode.com".to_string(),
node_type: NodeType::Direct,
description: "香港 G 线路(滴滴车".to_string(),
response_time: None,
available: None,
},
PackycodeNode {
name: "滴滴车 CF-Pro".to_string(),
url: "https://share-api-cf-pro.packycode.com".to_string(),
node_type: NodeType::Direct,
description: "CloudFlare Pro 线路(滴滴车)".to_string(),
response_time: None,
available: None,
},

View File

@@ -36,7 +36,7 @@ use commands::claude::{
use commands::mcp::{
mcp_add, mcp_add_from_claude_desktop, mcp_add_json, mcp_get, mcp_get_server_status, mcp_list,
mcp_read_project_config, mcp_remove, mcp_reset_project_choices, mcp_save_project_config,
mcp_serve, mcp_test_connection,
mcp_serve, mcp_test_connection, mcp_export_servers,
};
use commands::usage::{
@@ -349,6 +349,7 @@ fn main() {
mcp_get_server_status,
mcp_read_project_config,
mcp_save_project_config,
mcp_export_servers,
// Storage Management
storage_list_tables,

View File

@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Claudia",
"version": "1.2.0",
"version": "1.2.2",
"identifier": "claudia.asterisk.so",
"build": {
"beforeDevCommand": "bun run dev",
@@ -18,7 +18,7 @@
}
],
"security": {
"csp": "default-src 'self'; img-src 'self' asset: https://asset.localhost blob: data:; style-src 'self' 'unsafe-inline' blob: data: asset: https://asset.localhost; style-src-elem 'self' 'unsafe-inline' blob: data: asset: https://asset.localhost; style-src-attr 'self' 'unsafe-inline'; script-src 'self' 'unsafe-eval' https://app.posthog.com https://*.posthog.com https://*.i.posthog.com https://*.assets.i.posthog.com; worker-src 'self' blob: asset: https://asset.localhost; font-src 'self' data: blob: asset: https://asset.localhost; connect-src 'self' ipc: http://ipc.localhost https://ipc.localhost https://app.posthog.com https://*.posthog.com https://*.i.posthog.com",
"csp": "default-src 'self'; img-src 'self' asset: https://asset.localhost blob: data:; style-src 'self' 'unsafe-inline' blob: data: asset: https://asset.localhost; style-src-elem 'self' 'unsafe-inline' blob: data: asset: https://asset.localhost; style-src-attr 'self' 'unsafe-inline'; script-src 'self' 'unsafe-eval' https://app.posthog.com https://*.posthog.com https://*.i.posthog.com https://*.assets.i.posthog.com; worker-src 'self' blob: asset: https://asset.localhost; font-src 'self' data: blob: asset: https://asset.localhost; connect-src 'self' ipc: http://ipc.localhost https://ipc.localhost https://app.posthog.com https://*.posthog.com https://*.i.posthog.com https://api.packycode.com https://api-hk-cn2.packycode.com https://api-hk-g.packycode.com https://api-cf-pro.packycode.com https://share-api.packycode.com https://share-api-hk-cn2.packycode.com https://share-api-hk-g.packycode.com https://share-api-cf-pro.packycode.com",
"assetProtocol": {
"enable": true,
"scope": [
@@ -40,6 +40,7 @@
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico",
"icons/icon.png"
],
"resources": [],

View File

@@ -1,4 +1,4 @@
import { useState, useEffect } from "react";
import { useState, useEffect, lazy, Suspense } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Plus, Loader2, ArrowLeft } from "lucide-react";
import { api, type Project, type Session, type ClaudeMdFile } from "@/lib/api";
@@ -10,12 +10,8 @@ import { ProjectList } from "@/components/ProjectList";
import { SessionList } from "@/components/SessionList";
import { RunningClaudeSessions } from "@/components/RunningClaudeSessions";
import { Topbar } from "@/components/Topbar";
import { MarkdownEditor } from "@/components/MarkdownEditor";
import { ClaudeFileEditor } from "@/components/ClaudeFileEditor";
import { Settings } from "@/components/Settings";
import { CCAgents } from "@/components/CCAgents";
import { UsageDashboard } from "@/components/UsageDashboard";
import { MCPManager } from "@/components/MCPManager";
import { NFOCredits } from "@/components/NFOCredits";
import { ClaudeBinaryDialog } from "@/components/ClaudeBinaryDialog";
import { Toast, ToastContainer } from "@/components/ui/toast";
@@ -32,6 +28,12 @@ import RelayStationManager from "@/components/RelayStationManager";
import { CcrRouterManager } from "@/components/CcrRouterManager";
import i18n from "@/lib/i18n";
// Lazy load these components to match TabContent's dynamic imports
const MarkdownEditor = lazy(() => import('@/components/MarkdownEditor').then(m => ({ default: m.MarkdownEditor })));
const Settings = lazy(() => import('@/components/Settings').then(m => ({ default: m.Settings })));
const UsageDashboard = lazy(() => import('@/components/UsageDashboard').then(m => ({ default: m.UsageDashboard })));
const MCPManager = lazy(() => import('@/components/MCPManager').then(m => ({ default: m.MCPManager })));
type View =
| "welcome"
| "projects"
@@ -299,14 +301,18 @@ function AppContent() {
case "editor":
return (
<div className="flex-1 overflow-hidden">
<MarkdownEditor onBack={() => handleViewChange("welcome")} />
<Suspense fallback={<div className="flex items-center justify-center h-full"><Loader2 className="h-6 w-6 animate-spin" /></div>}>
<MarkdownEditor onBack={() => handleViewChange("welcome")} />
</Suspense>
</div>
);
case "settings":
return (
<div className="flex-1 flex flex-col" style={{ minHeight: 0 }}>
<Settings onBack={() => handleViewChange("welcome")} />
<Suspense fallback={<div className="flex items-center justify-center h-full"><Loader2 className="h-6 w-6 animate-spin" /></div>}>
<Settings onBack={() => handleViewChange("welcome")} />
</Suspense>
</div>
);
@@ -459,12 +465,16 @@ function AppContent() {
case "usage-dashboard":
return (
<UsageDashboard onBack={() => handleViewChange("welcome")} />
<Suspense fallback={<div className="flex items-center justify-center h-full"><Loader2 className="h-6 w-6 animate-spin" /></div>}>
<UsageDashboard onBack={() => handleViewChange("welcome")} />
</Suspense>
);
case "mcp":
return (
<MCPManager onBack={() => handleViewChange("welcome")} />
<Suspense fallback={<div className="flex items-center justify-center h-full"><Loader2 className="h-6 w-6 animate-spin" /></div>}>
<MCPManager onBack={() => handleViewChange("welcome")} />
</Suspense>
);
case "project-settings":

View File

@@ -29,6 +29,7 @@ export const MCPImportExport: React.FC<MCPImportExportProps> = ({
const [importingDesktop, setImportingDesktop] = useState(false);
const [importingJson, setImportingJson] = useState(false);
const [importScope, setImportScope] = useState("local");
const [exporting, setExporting] = useState(false);
/**
* Imports servers from Claude Desktop
@@ -142,11 +143,84 @@ export const MCPImportExport: React.FC<MCPImportExportProps> = ({
};
/**
* Handles exporting servers (placeholder)
* Handles exporting servers
*/
const handleExport = () => {
// TODO: Implement export functionality
onError("Export functionality coming soon!");
const handleExport = async () => {
try {
setExporting(true);
const result = await api.mcpExportServers();
if (result.servers.length === 0) {
onError("No MCP servers configured to export");
return;
}
let jsonContent: string;
let defaultFileName: string;
if (result.format === "single" && result.servers.length === 1) {
// Single server format
const server = result.servers[0];
const exportData: any = {
type: server.transport,
};
if (server.transport === "stdio") {
exportData.command = server.command;
exportData.args = server.args;
exportData.env = server.env;
} else if (server.transport === "sse") {
exportData.url = server.url;
}
jsonContent = JSON.stringify(exportData, null, 2);
defaultFileName = `mcp-server-${server.name}.json`;
} else {
// Multiple servers format
const exportData: any = {
mcpServers: {}
};
for (const server of result.servers) {
const serverConfig: any = {
command: server.command || "",
args: server.args,
env: server.env
};
if (server.transport === "sse") {
serverConfig.url = server.url;
}
exportData.mcpServers[server.name] = serverConfig;
}
jsonContent = JSON.stringify(exportData, null, 2);
defaultFileName = "mcp-servers.json";
}
// Use Tauri's save dialog
const { save } = await import('@tauri-apps/plugin-dialog');
const filePath = await save({
defaultPath: defaultFileName,
filters: [{
name: 'JSON',
extensions: ['json']
}]
});
if (filePath) {
// Use Tauri's file system API to write the file
const { writeTextFile } = await import('@tauri-apps/plugin-fs');
await writeTextFile(filePath, jsonContent);
onError(`Successfully exported ${result.servers.length} server(s) to ${filePath}`);
}
} catch (error: any) {
console.error("Failed to export servers:", error);
onError(error.toString() || "Failed to export servers");
} finally {
setExporting(false);
}
};
/**
@@ -273,12 +347,12 @@ export const MCPImportExport: React.FC<MCPImportExportProps> = ({
</div>
</Card>
{/* Export (Coming Soon) */}
<Card className="p-4 opacity-60">
{/* Export Configuration */}
<Card className="p-4 hover:bg-accent/5 transition-colors">
<div className="space-y-3">
<div className="flex items-start gap-3">
<div className="p-2.5 bg-muted rounded-lg">
<Upload className="h-5 w-5 text-muted-foreground" />
<div className="p-2.5 bg-green-500/10 rounded-lg">
<Upload className="h-5 w-5 text-green-500" />
</div>
<div className="flex-1">
<h4 className="text-sm font-medium">{t('mcp.exportConfiguration')}</h4>
@@ -289,12 +363,21 @@ export const MCPImportExport: React.FC<MCPImportExportProps> = ({
</div>
<Button
onClick={handleExport}
disabled={true}
variant="secondary"
disabled={exporting}
variant="outline"
className="w-full gap-2"
>
<Upload className="h-4 w-4" />
{t('mcp.exportComingSoon')}
{exporting ? (
<>
<Loader2 className="h-4 w-4 animate-spin" />
{t('mcp.exporting')}
</>
) : (
<>
<Upload className="h-4 w-4" />
{t('mcp.exportConfiguration')}
</>
)}
</Button>
</div>
</Card>

View File

@@ -385,21 +385,12 @@ const RelayStationManager: React.FC<RelayStationManagerProps> = ({ onBack }) =>
const isToggling = togglingEnable[station.id];
return (
<div className="flex items-center gap-2">
<Switch
checked={enabled}
disabled={isToggling}
onCheckedChange={() => toggleEnableStatus(station.id, enabled)}
className="data-[state=checked]:bg-green-500"
/>
{isToggling ? (
<Badge variant="secondary" className="animate-pulse">{t('common.updating')}</Badge>
) : enabled ? (
<Badge variant="default" className="bg-green-500">{t('status.enabled')}</Badge>
) : (
<Badge variant="secondary">{t('status.disabled')}</Badge>
)}
</div>
<Switch
checked={enabled}
disabled={isToggling}
onCheckedChange={() => toggleEnableStatus(station.id, enabled)}
className="data-[state=checked]:bg-green-500"
/>
);
};
@@ -691,75 +682,95 @@ const RelayStationManager: React.FC<RelayStationManagerProps> = ({ onBack }) =>
) : (
stations.map((station) => (
<Card key={station.id} className="relative">
<CardHeader className="pb-3">
<div className="flex justify-between items-start">
<div>
<CardTitle className="text-lg">{station.name}</CardTitle>
<CardDescription className="mt-1">
<CardHeader className="pb-2 pt-3 px-3">
<div className="flex justify-between items-center">
<div className="flex-1 min-w-0 mr-2">
<CardTitle className="text-sm font-medium">{station.name}</CardTitle>
<CardDescription className="text-xs mt-0.5">
{getAdapterDisplayName(station.adapter)}
</CardDescription>
</div>
{getStatusBadge(station)}
<div className="flex items-center gap-1">
{getStatusBadge(station)}
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={(e) => {
e.stopPropagation();
setSelectedStation(station);
setShowEditDialog(true);
}}
>
<Edit className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-red-500 hover:text-red-700"
onClick={(e) => {
e.stopPropagation();
openDeleteDialog(station);
}}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
</CardHeader>
<CardContent>
<div className="space-y-3">
<div className="flex items-center text-sm text-muted-foreground">
<Globe className="mr-2 h-4 w-4" />
{station.api_url}
<CardContent className="pt-1 pb-3 px-3">
<div className="space-y-2">
<div className="flex items-center text-xs text-muted-foreground">
<Globe className="mr-1.5 h-3 w-3" />
<span className="truncate">{station.api_url}</span>
</div>
{station.description && (
<p className="text-sm text-muted-foreground">
<p className="text-xs text-muted-foreground line-clamp-2">
{station.description}
</p>
)}
{/* PackyCode 额度显示 */}
{station.adapter === 'packycode' && (
<div className="mt-3 p-3 bg-blue-50 dark:bg-blue-950/30 rounded-lg border border-blue-200 dark:border-blue-900">
<div className="mt-2 p-2 bg-blue-50 dark:bg-blue-950/30 rounded-lg border border-blue-200 dark:border-blue-900">
{loadingQuota[station.id] ? (
<div className="flex items-center justify-center py-2">
<div className="h-4 w-4 animate-spin rounded-full border-b-2 border-blue-600"></div>
<span className="ml-2 text-sm text-muted-foreground">...</span>
<div className="flex items-center justify-center py-1">
<div className="h-3 w-3 animate-spin rounded-full border-b-2 border-blue-600"></div>
<span className="ml-2 text-xs text-muted-foreground">...</span>
</div>
) : quotaData[station.id] ? (
<div className="space-y-3">
<div className="space-y-2">
{/* 用户信息和计划 */}
<div className="flex items-center justify-between text-xs">
<div className="flex items-center gap-2">
<div className="flex items-center gap-1.5">
{quotaData[station.id].username && (
<span className="text-muted-foreground">{quotaData[station.id].username}</span>
)}
<Badge variant="secondary" className="text-xs">
<Badge variant="secondary" className="text-xs h-5 px-1.5">
{quotaData[station.id].plan_type.toUpperCase()}
</Badge>
{quotaData[station.id].opus_enabled && (
<Badge variant="default" className="text-xs bg-purple-600">
<Badge variant="default" className="text-xs h-5 px-1.5 bg-purple-600">
Opus
</Badge>
)}
</div>
{quotaData[station.id].plan_expires_at && (
<span className="text-muted-foreground">
: {new Date(quotaData[station.id].plan_expires_at!).toLocaleDateString()}
</span>
)}
</div>
{/* 账户余额 */}
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">:</span>
<span className="font-semibold text-blue-600">
<div className="flex items-center justify-between text-xs">
<span className="text-muted-foreground">:</span>
<span className="font-medium text-blue-600">
${Number(quotaData[station.id].balance_usd).toFixed(2)}
</span>
</div>
{/* 日额度 */}
<div className="space-y-1">
<div className="flex items-center justify-between text-sm">
<div className="space-y-0.5">
<div className="flex items-center justify-between text-xs">
<span className="text-muted-foreground">:</span>
<div className="flex items-center gap-2">
<div className="flex items-center gap-1">
{(() => {
const daily_spent = Number(quotaData[station.id].daily_spent_usd);
const daily_budget = Number(quotaData[station.id].daily_budget_usd);
@@ -768,8 +779,7 @@ const RelayStationManager: React.FC<RelayStationManagerProps> = ({ onBack }) =>
<span className={daily_spent > daily_budget * 0.8 ? 'text-orange-600' : 'text-green-600'}>
${daily_spent.toFixed(2)}
</span>
<span className="text-muted-foreground">/</span>
<span className="text-muted-foreground">${daily_budget.toFixed(2)}</span>
<span className="text-muted-foreground">/ ${daily_budget.toFixed(2)}</span>
</>
);
})()}
@@ -839,7 +849,7 @@ const RelayStationManager: React.FC<RelayStationManagerProps> = ({ onBack }) =>
<Button
variant="ghost"
size="sm"
className="h-5 px-2 text-xs"
className="h-6 px-2 text-xs"
onClick={(e) => {
e.stopPropagation();
fetchPackycodeQuota(station.id);
@@ -850,14 +860,15 @@ const RelayStationManager: React.FC<RelayStationManagerProps> = ({ onBack }) =>
</div>
</div>
) : (
<div className="text-center py-2">
<div className="text-center py-1">
<Button
variant="outline"
variant="ghost"
size="sm"
onClick={(e) => {
e.stopPropagation();
fetchPackycodeQuota(station.id);
}}
className="h-7 text-xs px-2"
>
</Button>
@@ -866,30 +877,6 @@ const RelayStationManager: React.FC<RelayStationManagerProps> = ({ onBack }) =>
</div>
)}
<div className="flex justify-end">
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.stopPropagation();
setSelectedStation(station);
setShowEditDialog(true);
}}
>
<Edit className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.stopPropagation();
openDeleteDialog(station);
}}
className="text-red-500 hover:text-red-700"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
</CardContent>
</Card>
@@ -1145,7 +1132,52 @@ const CreateStationDialog: React.FC<{
try {
setSubmitting(true);
await api.relayStationCreate(formData);
// PackyCode 保存时自动选择最佳节点
if (formData.adapter === 'packycode') {
let finalApiUrl = formData.api_url;
if (packycodeService === 'bus') {
// 公交车自动选择
const busNodes = [
{ url: "https://api.packycode.com", name: "🚌 公交车默认节点" },
{ url: "https://api-hk-cn2.packycode.com", name: "🇭🇰 公交车 HK-CN2" },
{ url: "https://api-hk-g.packycode.com", name: "🇭🇰 公交车 HK-G" },
{ url: "https://api-cf-pro.packycode.com", name: "☁️ 公交车 CF-Pro" }
];
await performSpeedTest(busNodes, (bestNode) => {
finalApiUrl = bestNode.url;
setPackycodeNode(bestNode.url);
});
} else if (packycodeService === 'taxi') {
// 滴滴车自动选择
const taxiNodes = [
{ url: "https://share-api.packycode.com", name: "🚗 滴滴车默认节点" },
{ url: "https://share-api-hk-cn2.packycode.com", name: "🇭🇰 滴滴车 HK-CN2" },
{ url: "https://share-api-hk-g.packycode.com", name: "🇭🇰 滴滴车 HK-G" },
{ url: "https://share-api-cf-pro.packycode.com", name: "☁️ 滴滴车 CF-Pro" }
];
await performSpeedTest(taxiNodes, (bestNode) => {
finalApiUrl = bestNode.url;
setPackycodeTaxiNode(bestNode.url);
});
}
// 使用选择的最佳节点创建中转站
await api.relayStationCreate({
...formData,
api_url: finalApiUrl,
adapter_config: {
service_type: packycodeService
}
});
} else {
// 非 PackyCode 适配器直接创建
await api.relayStationCreate(formData);
}
onSuccess();
} catch (error) {
console.error('Failed to create station:', error);
@@ -1388,31 +1420,16 @@ const CreateStationDialog: React.FC<{
</SelectTrigger>
<SelectContent>
<SelectItem value="https://api.packycode.com">
🚌 1
🚌
</SelectItem>
<SelectItem value="https://api-hk-cn2.packycode.com">
🇭🇰 2 (HK-CN2)
🇭🇰 HK-CN2
</SelectItem>
<SelectItem value="https://api-us-cmin2.packycode.com">
🇺🇸 3 (US-CMIN2)
</SelectItem>
<SelectItem value="https://api-us-4837.packycode.com">
🇺🇸 4 (US-4837)
</SelectItem>
<SelectItem value="https://api-us-cn2.packycode.com">
🔄 1 (US-CN2)
<SelectItem value="https://api-hk-g.packycode.com">
🇭🇰 HK-G
</SelectItem>
<SelectItem value="https://api-cf-pro.packycode.com">
2 (CF-Pro)
</SelectItem>
<SelectItem value="https://api-test.packyme.com" disabled>
1
</SelectItem>
<SelectItem value="https://api-test-custom.packycode.com" disabled>
2
</SelectItem>
<SelectItem value="https://api-tmp-test.dzz.ai" disabled>
3
CF-Pro
</SelectItem>
</SelectContent>
</Select>
@@ -1422,12 +1439,10 @@ const CreateStationDialog: React.FC<{
variant="outline"
onClick={async () => {
const busNodes = [
{ url: "https://api.packycode.com", name: "🚌 直连1默认公交车" },
{ url: "https://api-hk-cn2.packycode.com", name: "🇭🇰 直连2 (HK-CN2)" },
{ url: "https://api-us-cmin2.packycode.com", name: "🇺🇸 直连3 (US-CMIN2)" },
{ url: "https://api-us-4837.packycode.com", name: "🇺🇸 直连4 (US-4837)" },
{ url: "https://api-us-cn2.packycode.com", name: "🔄 备用1 (US-CN2)" },
{ url: "https://api-cf-pro.packycode.com", name: "☁️ 备用2 (CF-Pro)" }
{ url: "https://api.packycode.com", name: "🚌 公交车默认节点" },
{ url: "https://api-hk-cn2.packycode.com", name: "🇭🇰 公交车 HK-CN2" },
{ url: "https://api-hk-g.packycode.com", name: "🇭🇰 公交车 HK-G" },
{ url: "https://api-cf-pro.packycode.com", name: "☁️ 公交车 CF-Pro" }
];
await performSpeedTest(busNodes, (bestNode) => {
@@ -1464,13 +1479,16 @@ const CreateStationDialog: React.FC<{
</SelectTrigger>
<SelectContent>
<SelectItem value="https://share-api.packycode.com">
🚗 1
</SelectItem>
<SelectItem value="https://share-api-cf-pro.packycode.com">
1 (CF-Pro)
🚗
</SelectItem>
<SelectItem value="https://share-api-hk-cn2.packycode.com">
🇭🇰 2 (HK-CN2)
🇭🇰 HK-CN2
</SelectItem>
<SelectItem value="https://share-api-hk-g.packycode.com">
🇭🇰 HK-G
</SelectItem>
<SelectItem value="https://share-api-cf-pro.packycode.com">
CF-Pro
</SelectItem>
</SelectContent>
</Select>
@@ -1480,9 +1498,10 @@ const CreateStationDialog: React.FC<{
variant="outline"
onClick={async () => {
const taxiNodes = [
{ url: "https://share-api.packycode.com", name: "🚗 直连1默认滴滴车" },
{ url: "https://share-api-cf-pro.packycode.com", name: "☁️ 备用1 (CF-Pro)" },
{ url: "https://share-api-hk-cn2.packycode.com", name: "🇭🇰 备用2 (HK-CN2)" }
{ url: "https://share-api.packycode.com", name: "🚗 滴滴车默认节点" },
{ url: "https://share-api-hk-cn2.packycode.com", name: "🇭🇰 滴滴车 HK-CN2" },
{ url: "https://share-api-hk-g.packycode.com", name: "🇭🇰 滴滴车 HK-G" },
{ url: "https://share-api-cf-pro.packycode.com", name: "☁️ 滴滴车 CF-Pro" }
];
await performSpeedTest(taxiNodes, (bestNode) => {
@@ -1718,7 +1737,7 @@ const EditStationDialog: React.FC<{
// PackyCode 特定状态
const [packycodeService, setPackycodeService] = useState<string>(() => {
// 从API URL判断服务类型
if (station.adapter === 'packycode' && station.api_url.includes('share-api')) {
if (station.adapter === 'packycode' && (station.api_url.includes('share-api') || station.api_url.includes('codex-api'))) {
return 'taxi';
}
return 'bus';
@@ -1730,6 +1749,13 @@ const EditStationDialog: React.FC<{
}
return 'https://api.packycode.com';
});
const [packycodeTaxiNode, setPackycodeTaxiNode] = useState<string>(() => {
// 如果是PackyCode滴滴车使用当前的API URL
if (station.adapter === 'packycode' && (station.api_url.includes('share-api') || station.api_url.includes('codex-api'))) {
return station.api_url;
}
return 'https://share-api.packycode.com';
});
const [showSpeedTestModal, setShowSpeedTestModal] = useState(false);
const [speedTestResults, setSpeedTestResults] = useState<{ url: string; name: string; responseTime: number | null; status: 'testing' | 'success' | 'failed' }[]>([]);
@@ -1876,7 +1902,157 @@ const EditStationDialog: React.FC<{
try {
setSubmitting(true);
await api.relayStationUpdate(formData);
// PackyCode 保存时自动选择最佳节点
if (formData.adapter === 'packycode') {
let finalApiUrl = formData.api_url;
if (packycodeService === 'bus') {
// 公交车自动选择
const busNodes = [
{ url: "https://api.packycode.com", name: "🚌 公交车默认节点" },
{ url: "https://api-hk-cn2.packycode.com", name: "🇭🇰 公交车 HK-CN2" },
{ url: "https://api-hk-g.packycode.com", name: "🇭🇰 公交车 HK-G" },
{ url: "https://api-cf-pro.packycode.com", name: "☁️ 公交车 CF-Pro" }
];
await new Promise<void>((resolve) => {
// 内联的测速逻辑
setShowSpeedTestModal(true);
setSpeedTestInProgress(true);
const initialResults = busNodes.map(node => ({
url: node.url,
name: node.name,
responseTime: null,
status: 'testing' as const
}));
setSpeedTestResults(initialResults);
let bestNode = busNodes[0];
let minTime = Infinity;
const testPromises = busNodes.map(async (node, index) => {
try {
const startTime = Date.now();
await fetch(node.url, {
method: 'HEAD',
mode: 'no-cors'
});
const responseTime = Date.now() - startTime;
setSpeedTestResults(prev => prev.map((result, i) =>
i === index ? { ...result, responseTime, status: 'success' } : result
));
if (responseTime < minTime) {
minTime = responseTime;
bestNode = node;
}
return { node, responseTime };
} catch (error) {
console.log(`Node ${node.url} failed:`, error);
setSpeedTestResults(prev => prev.map((result, i) =>
i === index ? { ...result, responseTime: null, status: 'failed' } : result
));
return { node, responseTime: null };
}
});
Promise.all(testPromises).then(() => {
setTimeout(() => {
setSpeedTestInProgress(false);
finalApiUrl = bestNode.url;
setPackycodeNode(bestNode.url);
setTimeout(() => {
setShowSpeedTestModal(false);
resolve();
}, 1000);
}, 2000);
});
});
} else if (packycodeService === 'taxi') {
// 滴滴车自动选择
const taxiNodes = [
{ url: "https://share-api.packycode.com", name: "🚗 滴滴车默认节点" },
{ url: "https://share-api-hk-cn2.packycode.com", name: "🇭🇰 滴滴车 HK-CN2" },
{ url: "https://share-api-hk-g.packycode.com", name: "🇭🇰 滴滴车 HK-G" },
{ url: "https://share-api-cf-pro.packycode.com", name: "☁️ 滴滴车 CF-Pro" }
];
await new Promise<void>((resolve) => {
// 内联的测速逻辑
setShowSpeedTestModal(true);
setSpeedTestInProgress(true);
const initialResults = taxiNodes.map(node => ({
url: node.url,
name: node.name,
responseTime: null,
status: 'testing' as const
}));
setSpeedTestResults(initialResults);
let bestNode = taxiNodes[0];
let minTime = Infinity;
const testPromises = taxiNodes.map(async (node, index) => {
try {
const startTime = Date.now();
await fetch(node.url, {
method: 'HEAD',
mode: 'no-cors'
});
const responseTime = Date.now() - startTime;
setSpeedTestResults(prev => prev.map((result, i) =>
i === index ? { ...result, responseTime, status: 'success' } : result
));
if (responseTime < minTime) {
minTime = responseTime;
bestNode = node;
}
return { node, responseTime };
} catch (error) {
console.log(`Node ${node.url} failed:`, error);
setSpeedTestResults(prev => prev.map((result, i) =>
i === index ? { ...result, responseTime: null, status: 'failed' } : result
));
return { node, responseTime: null };
}
});
Promise.all(testPromises).then(() => {
setTimeout(() => {
setSpeedTestInProgress(false);
finalApiUrl = bestNode.url;
setPackycodeTaxiNode(bestNode.url);
setFormData(prev => ({ ...prev, api_url: bestNode.url }));
setTimeout(() => {
setShowSpeedTestModal(false);
resolve();
}, 1000);
}, 2000);
});
});
}
// 使用选择的最佳节点更新中转站
await api.relayStationUpdate({
...formData,
api_url: finalApiUrl,
adapter_config: {
service_type: packycodeService
}
});
} else {
// 非 PackyCode 适配器直接更新
await api.relayStationUpdate(formData);
}
onSuccess();
} catch (error) {
console.error('Failed to update station:', error);
@@ -2144,12 +2320,10 @@ const EditStationDialog: React.FC<{
variant="outline"
onClick={async () => {
const busNodes = [
{ url: "https://api.packycode.com", name: "🚌 直连1默认公交车" },
{ url: "https://api-hk-cn2.packycode.com", name: "🇭🇰 直连2 (HK-CN2)" },
{ url: "https://api-us-cmin2.packycode.com", name: "🇺🇸 直连3 (US-CMIN2)" },
{ url: "https://api-us-4837.packycode.com", name: "🇺🇸 直连4 (US-4837)" },
{ url: "https://api-us-cn2.packycode.com", name: "🔄 备用1 (US-CN2)" },
{ url: "https://api-cf-pro.packycode.com", name: "☁️ 备用2 (CF-Pro)" }
{ url: "https://api.packycode.com", name: "🚌 公交车默认节点" },
{ url: "https://api-hk-cn2.packycode.com", name: "🇭🇰 公交车 HK-CN2" },
{ url: "https://api-hk-g.packycode.com", name: "🇭🇰 公交车 HK-G" },
{ url: "https://api-cf-pro.packycode.com", name: "☁️ 公交车 CF-Pro" }
];
await performSpeedTest(busNodes, (bestNode) => {
@@ -2168,6 +2342,122 @@ const EditStationDialog: React.FC<{
</div>
)}
{formData.adapter === 'packycode' && packycodeService === 'taxi' && (
<div className="space-y-2">
<Label>{t('relayStation.nodeSelection')}</Label>
<div className="space-y-2">
<div className="flex gap-2">
<div className="flex-1">
<Select
value={packycodeTaxiNode}
onValueChange={(value: string) => {
setPackycodeTaxiNode(value);
setFormData(prev => ({ ...prev, api_url: value }));
}}
>
<SelectTrigger>
<SelectValue placeholder={t('relayStation.selectNode')} />
</SelectTrigger>
<SelectContent>
<SelectItem value="https://share-api.packycode.com">
🚗
</SelectItem>
<SelectItem value="https://share-api-hk-cn2.packycode.com">
🇭🇰 HK-CN2
</SelectItem>
<SelectItem value="https://share-api-hk-g.packycode.com">
🇭🇰 HK-G
</SelectItem>
<SelectItem value="https://share-api-cf-pro.packycode.com">
CF-Pro
</SelectItem>
</SelectContent>
</Select>
</div>
<Button
type="button"
variant="outline"
onClick={async () => {
const taxiNodes = [
{ url: "https://share-api.packycode.com", name: "🚗 滴滴车默认节点" },
{ url: "https://share-api-hk-cn2.packycode.com", name: "🇭🇰 滴滴车 HK-CN2" },
{ url: "https://share-api-hk-g.packycode.com", name: "🇭🇰 滴滴车 HK-G" },
{ url: "https://share-api-cf-pro.packycode.com", name: "☁️ 滴滴车 CF-Pro" }
];
// 复制 performSpeedTest 逻辑,因为它在这个作用域中不可用
setShowSpeedTestModal(true);
setSpeedTestInProgress(true);
const initialResults = taxiNodes.map(node => ({
url: node.url,
name: node.name,
responseTime: null,
status: 'testing' as const
}));
setSpeedTestResults(initialResults);
let bestNode = taxiNodes[0];
let minTime = Infinity;
const testPromises = taxiNodes.map(async (node, index) => {
try {
const startTime = Date.now();
await fetch(node.url, {
method: 'HEAD',
mode: 'no-cors'
});
const responseTime = Date.now() - startTime;
setSpeedTestResults(prev => prev.map((result, i) =>
i === index ? { ...result, responseTime, status: 'success' } : result
));
if (responseTime < minTime) {
minTime = responseTime;
bestNode = node;
}
return { node, responseTime };
} catch (error) {
console.log(`Node ${node.url} failed:`, error);
setSpeedTestResults(prev => prev.map((result, i) =>
i === index ? { ...result, responseTime: null, status: 'failed' } : result
));
return { node, responseTime: null };
}
});
try {
await Promise.all(testPromises);
setTimeout(() => {
setSpeedTestInProgress(false);
setPackycodeTaxiNode(bestNode.url);
setFormData(prev => ({ ...prev, api_url: bestNode.url }));
setTimeout(() => {
setShowSpeedTestModal(false);
}, 1000);
}, 2000);
} catch (error) {
console.error('Speed test failed:', error);
setSpeedTestInProgress(false);
setTimeout(() => {
setShowSpeedTestModal(false);
}, 1000);
}
}}
>
</Button>
</div>
<p className="text-xs text-muted-foreground">
{t('relayStation.selectedNode') + ': ' + packycodeTaxiNode}
</p>
</div>
</div>
)}
<div className="space-y-2">
<Label htmlFor="edit-description">{t('relayStation.description')}</Label>
<Textarea

View File

@@ -1725,6 +1725,29 @@ export const api = {
}
},
/**
* Export configuration for MCP server
*/
async mcpExportServers(): Promise<{
servers: Array<{
name: string;
transport: string;
command?: string;
args: string[];
env: Record<string, string>;
url?: string;
scope: string;
}>;
format: string;
}> {
try {
return await invoke("mcp_export_servers");
} catch (error) {
console.error("Failed to export MCP servers:", error);
throw error;
}
},
/**
* Get the stored Claude binary path from settings
* @returns Promise resolving to the path if set, null otherwise

View File

@@ -512,6 +512,7 @@
"importFromClaudeDesktop": "Import from Claude Desktop",
"importFromClaudeDesktopDescription": "Automatically imports all MCP servers from Claude Desktop. Installs to user scope (available across all projects).",
"importing": "Importing...",
"exporting": "Exporting...",
"importFromJSON": "Import from JSON",
"importFromJSONDescription": "Import server configuration from a JSON file",
"chooseJSONFile": "Choose JSON File",

View File

@@ -494,6 +494,7 @@
"importFromClaudeDesktop": "从 Claude Desktop 导入",
"importFromClaudeDesktopDescription": "自动导入 Claude Desktop 中的所有 MCP 服务器。安装到用户范围(所有项目可用)。",
"importing": "导入中...",
"exporting": "导出中...",
"importFromJSON": "从 JSON 导入",
"importFromJSONDescription": "从 JSON 文件导入服务器配置",
"chooseJSONFile": "选择 JSON 文件",