Compare commits
6 Commits
Author | SHA1 | Date | |
---|---|---|---|
4cdb22788f | |||
3456f9e06d | |||
564d7a29fb | |||
77837d3656 | |||
6ef45f328c | |||
0e78b08549 |
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "claudia",
|
||||
"private": true,
|
||||
"version": "1.1.0",
|
||||
"version": "1.2.0",
|
||||
"license": "AGPL-3.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
2
src-tauri/Cargo.lock
generated
2
src-tauri/Cargo.lock
generated
@@ -718,7 +718,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "claudia"
|
||||
version = "1.1.0"
|
||||
version = "1.2.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "claudia"
|
||||
version = "1.1.0"
|
||||
version = "1.2.0"
|
||||
description = "GUI app and Toolkit for Claude Code"
|
||||
authors = ["mufeedvh", "123vviekr"]
|
||||
license = "AGPL-3.0"
|
||||
|
@@ -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>
|
||||
|
@@ -1,6 +1,13 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::process::{Command, Stdio};
|
||||
use log::{debug, error, info};
|
||||
use std::net::TcpStream;
|
||||
use std::time::Duration;
|
||||
use once_cell::sync::Lazy;
|
||||
use std::sync::Mutex;
|
||||
|
||||
// 全局变量存储找到的 CCR 路径
|
||||
static CCR_PATH: Lazy<Mutex<Option<String>>> = Lazy::new(|| Mutex::new(None));
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct CcrServiceStatus {
|
||||
@@ -10,6 +17,7 @@ pub struct CcrServiceStatus {
|
||||
pub has_ccr_binary: bool,
|
||||
pub ccr_version: Option<String>,
|
||||
pub process_id: Option<u32>,
|
||||
pub raw_output: Option<String>, // 添加原始输出用于调试
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
@@ -18,39 +26,512 @@ 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<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();
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
// macOS 特定路径
|
||||
// 常见全局 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")]
|
||||
{
|
||||
// Windows 特定路径
|
||||
let program_files = std::env::var("ProgramFiles").unwrap_or_else(|_| "C:\\Program Files".to_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));
|
||||
|
||||
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 特定路径
|
||||
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> {
|
||||
// 先检查缓存
|
||||
if let Ok(cached) = CCR_PATH.lock() {
|
||||
if cached.is_some() {
|
||||
return cached.clone();
|
||||
}
|
||||
}
|
||||
|
||||
// 硬编码检查最常见的路径(针对打包应用的特殊处理)
|
||||
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 {
|
||||
// 处理通配符路径 (仅限 Unix-like 系统)
|
||||
if path.contains('*') {
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
{
|
||||
if let Ok(entries) = glob::glob(path) {
|
||||
for entry in entries.flatten() {
|
||||
let path_str = entry.to_string_lossy().to_string();
|
||||
if test_ccr_command(&path_str) {
|
||||
if let Ok(mut cached) = CCR_PATH.lock() {
|
||||
*cached = Some(path_str.clone());
|
||||
}
|
||||
info!("Found ccr at: {}", path_str);
|
||||
return Some(path_str);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if test_ccr_command(path) {
|
||||
if let Ok(mut cached) = CCR_PATH.lock() {
|
||||
*cached = Some(path.clone());
|
||||
}
|
||||
info!("Found ccr at: {}", path);
|
||||
return Some(path.clone());
|
||||
}
|
||||
}
|
||||
|
||||
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 path_obj = std::path::Path::new(path);
|
||||
if !path_obj.exists() {
|
||||
debug!("CCR path does not exist: {}", path);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 如果是符号链接,解析真实路径
|
||||
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> {
|
||||
// 直接尝试执行 ccr --version 命令来检测是否安装
|
||||
// 这比使用 which 命令更可靠,特别是在打包后的应用中
|
||||
let output = Command::new("ccr")
|
||||
.arg("--version")
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.output();
|
||||
|
||||
match output {
|
||||
Ok(result) => Ok(result.status.success()),
|
||||
Err(e) => {
|
||||
// 如果命令执行失败,可能是因为 ccr 未安装或不在 PATH 中
|
||||
debug!("CCR installation check failed: {}", e);
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
let path = find_ccr_path();
|
||||
info!("CCR installation check result: {:?}", path);
|
||||
Ok(path.is_some())
|
||||
}
|
||||
|
||||
/// 获取 CCR 版本信息
|
||||
#[tauri::command]
|
||||
pub async fn get_ccr_version() -> Result<String, String> {
|
||||
let ccr_path = find_ccr_path().ok_or("CCR not found")?;
|
||||
|
||||
// 尝试多个版本命令参数
|
||||
let version_args = vec!["--version", "-v", "version"];
|
||||
|
||||
for arg in version_args {
|
||||
let output = Command::new("ccr")
|
||||
.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() {
|
||||
@@ -74,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,
|
||||
@@ -81,19 +670,38 @@ pub async fn get_ccr_service_status() -> Result<CcrServiceStatus, String> {
|
||||
has_ccr_binary: false,
|
||||
ccr_version: None,
|
||||
process_id: None,
|
||||
raw_output: Some(debug_info),
|
||||
});
|
||||
}
|
||||
|
||||
// 获取版本信息
|
||||
let ccr_version = get_ccr_version().await.ok();
|
||||
debug!("CCR version: {:?}", ccr_version);
|
||||
|
||||
// 获取 CCR 路径
|
||||
let ccr_path = find_ccr_path().ok_or("CCR not found")?;
|
||||
|
||||
// 检查服务状态
|
||||
let output = Command::new("ccr")
|
||||
.arg("status")
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.output();
|
||||
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
|
||||
};
|
||||
|
||||
info!("Executing ccr status command at path: {}", ccr_path);
|
||||
let output = cmd.output();
|
||||
|
||||
let output = match output {
|
||||
Ok(o) => o,
|
||||
@@ -106,6 +714,7 @@ pub async fn get_ccr_service_status() -> Result<CcrServiceStatus, String> {
|
||||
has_ccr_binary: true,
|
||||
ccr_version,
|
||||
process_id: None,
|
||||
raw_output: None,
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -113,15 +722,27 @@ pub async fn get_ccr_service_status() -> Result<CcrServiceStatus, String> {
|
||||
let status_output = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr_output = String::from_utf8_lossy(&output.stderr);
|
||||
|
||||
debug!("CCR status stdout: {}", status_output);
|
||||
debug!("CCR status stderr: {}", stderr_output);
|
||||
info!("CCR status command exit code: {:?}", output.status.code());
|
||||
info!("CCR status stdout length: {}", status_output.len());
|
||||
info!("CCR status stdout: {}", status_output);
|
||||
info!("CCR status stderr: {}", stderr_output);
|
||||
|
||||
// 更宽松的运行状态检测
|
||||
let is_running = output.status.success() &&
|
||||
(status_output.contains("Running") ||
|
||||
status_output.contains("running") ||
|
||||
status_output.contains("✅") ||
|
||||
status_output.contains("Port:"));
|
||||
// 检查状态 - 明确检测运行和停止状态
|
||||
let is_running = if status_output.contains("❌") || status_output.contains("Status: Not Running") {
|
||||
// 明确显示未运行
|
||||
false
|
||||
} else if status_output.contains("✅") || status_output.contains("Status: Running") {
|
||||
// 明确显示运行中
|
||||
true
|
||||
} else if status_output.contains("Process ID:") && status_output.contains("Port:") {
|
||||
// 包含进程ID和端口信息,可能在运行
|
||||
true
|
||||
} else {
|
||||
// 默认认为未运行
|
||||
false
|
||||
};
|
||||
|
||||
info!("CCR service running detection - is_running: {}", is_running);
|
||||
|
||||
// 尝试从输出中提取端口、端点和进程ID信息
|
||||
let mut port = None;
|
||||
@@ -131,15 +752,20 @@ pub async fn get_ccr_service_status() -> Result<CcrServiceStatus, String> {
|
||||
if is_running {
|
||||
// 提取端口信息 - 支持多种格式
|
||||
for line in status_output.lines() {
|
||||
if line.contains("Port:") || line.contains("port:") {
|
||||
// 尝试提取端口号
|
||||
if let Some(port_str) = line.split(':').last() {
|
||||
// 清理字符串,只保留数字
|
||||
let cleaned: String = port_str.chars()
|
||||
.filter(|c| c.is_numeric())
|
||||
.collect();
|
||||
if let Ok(port_num) = cleaned.parse::<u16>() {
|
||||
info!("Parsing line for port: {}", line);
|
||||
|
||||
// 检查是否包含端口信息
|
||||
if line.contains("Port:") || line.contains("port:") || line.contains("端口:") || line.contains("🌐") {
|
||||
// 查找数字
|
||||
let numbers: String = line.chars()
|
||||
.skip_while(|c| !c.is_numeric())
|
||||
.take_while(|c| c.is_numeric())
|
||||
.collect();
|
||||
|
||||
if !numbers.is_empty() {
|
||||
if let Ok(port_num) = numbers.parse::<u16>() {
|
||||
port = Some(port_num);
|
||||
info!("Successfully extracted port: {}", port_num);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -148,7 +774,9 @@ pub async fn get_ccr_service_status() -> Result<CcrServiceStatus, String> {
|
||||
|
||||
// 提取API端点信息 - 支持多种格式
|
||||
for line in status_output.lines() {
|
||||
if line.contains("API Endpoint:") || line.contains("Endpoint:") || line.contains("http://") || line.contains("https://") {
|
||||
info!("Parsing line for endpoint: {}", line);
|
||||
if line.contains("API Endpoint:") || line.contains("Endpoint:") ||
|
||||
line.contains("http://") || line.contains("https://") || line.contains("📡") {
|
||||
// 尝试提取URL
|
||||
if let Some(start) = line.find("http") {
|
||||
let url_part = &line[start..];
|
||||
@@ -157,6 +785,7 @@ pub async fn get_ccr_service_status() -> Result<CcrServiceStatus, String> {
|
||||
let url = &url_part[..end];
|
||||
if url.contains(":") && (url.contains("localhost") || url.contains("127.0.0.1")) {
|
||||
endpoint = Some(url.to_string());
|
||||
info!("Successfully extracted endpoint: {}", url);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -165,15 +794,18 @@ pub async fn get_ccr_service_status() -> Result<CcrServiceStatus, String> {
|
||||
|
||||
// 提取进程ID信息 - 支持多种格式
|
||||
for line in status_output.lines() {
|
||||
if line.contains("Process ID:") || line.contains("PID:") || line.contains("pid:") {
|
||||
// 尝试提取PID
|
||||
if let Some(pid_str) = line.split(':').last() {
|
||||
// 清理字符串,只保留数字
|
||||
let cleaned: String = pid_str.chars()
|
||||
.filter(|c| c.is_numeric())
|
||||
.collect();
|
||||
if let Ok(pid_num) = cleaned.parse::<u32>() {
|
||||
info!("Parsing line for PID: {}", line);
|
||||
if line.contains("Process ID:") || line.contains("PID:") || line.contains("pid:") || line.contains("🆔") {
|
||||
// 查找数字
|
||||
let numbers: String = line.chars()
|
||||
.skip_while(|c| !c.is_numeric())
|
||||
.take_while(|c| c.is_numeric())
|
||||
.collect();
|
||||
|
||||
if !numbers.is_empty() {
|
||||
if let Ok(pid_num) = numbers.parse::<u32>() {
|
||||
process_id = Some(pid_num);
|
||||
info!("Successfully extracted PID: {}", pid_num);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -192,6 +824,29 @@ pub async fn get_ccr_service_status() -> Result<CcrServiceStatus, String> {
|
||||
}
|
||||
}
|
||||
|
||||
// 如果命令失败或无法确定状态,尝试通过端口检查
|
||||
if !is_running {
|
||||
info!("Status command didn't detect running service, checking port 3456...");
|
||||
// 尝试连接默认端口
|
||||
match TcpStream::connect_timeout(&"127.0.0.1:3456".parse().unwrap(), Duration::from_secs(1)) {
|
||||
Ok(_) => {
|
||||
info!("Port 3456 is open, service appears to be running");
|
||||
return Ok(CcrServiceStatus {
|
||||
is_running: true,
|
||||
port: Some(3456),
|
||||
endpoint: Some("http://127.0.0.1:3456".to_string()),
|
||||
has_ccr_binary: true,
|
||||
ccr_version,
|
||||
process_id: None,
|
||||
raw_output: Some(status_output.to_string()),
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
info!("Port 3456 check failed: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(CcrServiceStatus {
|
||||
is_running,
|
||||
port,
|
||||
@@ -199,6 +854,7 @@ pub async fn get_ccr_service_status() -> Result<CcrServiceStatus, String> {
|
||||
has_ccr_binary,
|
||||
ccr_version,
|
||||
process_id,
|
||||
raw_output: Some(status_output.to_string()),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -210,6 +866,9 @@ pub async fn start_ccr_service() -> Result<CcrServiceInfo, String> {
|
||||
return Err("CCR is not installed. Please install claude-code-router first.".to_string());
|
||||
}
|
||||
|
||||
// 获取 CCR 路径
|
||||
let ccr_path = find_ccr_path().ok_or("CCR not found")?;
|
||||
|
||||
// 检查当前状态
|
||||
let current_status = get_ccr_service_status().await?;
|
||||
if current_status.is_running {
|
||||
@@ -220,8 +879,9 @@ pub async fn start_ccr_service() -> Result<CcrServiceInfo, String> {
|
||||
}
|
||||
|
||||
// 启动服务
|
||||
let _output = Command::new("ccr")
|
||||
let _output = Command::new(&ccr_path)
|
||||
.arg("start")
|
||||
.env("PATH", get_extended_path())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
@@ -250,8 +910,12 @@ pub async fn stop_ccr_service() -> Result<CcrServiceInfo, String> {
|
||||
return Err("CCR is not installed".to_string());
|
||||
}
|
||||
|
||||
let output = Command::new("ccr")
|
||||
// 获取 CCR 路径
|
||||
let ccr_path = find_ccr_path().ok_or("CCR not found")?;
|
||||
|
||||
let output = Command::new(&ccr_path)
|
||||
.arg("stop")
|
||||
.env("PATH", get_extended_path())
|
||||
.output()
|
||||
.map_err(|e| format!("Failed to stop ccr service: {}", e))?;
|
||||
|
||||
@@ -276,8 +940,12 @@ pub async fn restart_ccr_service() -> Result<CcrServiceInfo, String> {
|
||||
return Err("CCR is not installed".to_string());
|
||||
}
|
||||
|
||||
let output = Command::new("ccr")
|
||||
// 获取 CCR 路径
|
||||
let ccr_path = find_ccr_path().ok_or("CCR not found")?;
|
||||
|
||||
let output = Command::new(&ccr_path)
|
||||
.arg("restart")
|
||||
.env("PATH", get_extended_path())
|
||||
.output()
|
||||
.map_err(|e| format!("Failed to restart ccr service: {}", e))?;
|
||||
|
||||
@@ -314,9 +982,13 @@ pub async fn open_ccr_ui() -> Result<String, String> {
|
||||
tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
|
||||
}
|
||||
|
||||
// 获取 CCR 路径
|
||||
let ccr_path = find_ccr_path().ok_or("CCR not found")?;
|
||||
|
||||
// 执行 ccr ui 命令
|
||||
let _output = Command::new("ccr")
|
||||
let _output = Command::new(&ccr_path)
|
||||
.arg("ui")
|
||||
.env("PATH", get_extended_path())
|
||||
.spawn()
|
||||
.map_err(|e| format!("Failed to open ccr ui: {}", e))?;
|
||||
|
||||
@@ -334,4 +1006,4 @@ pub async fn get_ccr_config_path() -> Result<String, String> {
|
||||
.join("config.json");
|
||||
|
||||
Ok(config_path.to_string_lossy().to_string())
|
||||
}
|
||||
}
|
||||
|
@@ -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,
|
||||
})
|
||||
}
|
||||
|
@@ -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,
|
||||
|
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "Claudia",
|
||||
"version": "1.1.0",
|
||||
"version": "1.2.0",
|
||||
"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-us-cmin2.packycode.com https://api-us-4837.packycode.com https://api-us-cn2.packycode.com https://api-cf-pro.packycode.com https://share-api.packycode.com https://share-api-cf-pro.packycode.com https://share-api-hk-cn2.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": [],
|
||||
|
@@ -28,6 +28,8 @@ export function CcrRouterManager({ onBack }: CcrRouterManagerProps) {
|
||||
try {
|
||||
setLoading(true);
|
||||
const status = await ccrApi.getServiceStatus();
|
||||
console.log("CCR service status:", status);
|
||||
console.log("CCR raw output:", status.raw_output);
|
||||
setServiceStatus(status);
|
||||
} catch (error) {
|
||||
console.error("Failed to load CCR service status:", error);
|
||||
@@ -411,7 +413,7 @@ export function CcrRouterManager({ onBack }: CcrRouterManagerProps) {
|
||||
需要先安装 Claude Code Router 才能使用此功能
|
||||
</p>
|
||||
<Button
|
||||
onClick={() => open("https://www.npmjs.com/package/@musistudio/claude-code-router")}
|
||||
onClick={() => open("https://github.com/musistudio/claude-code-router/tree/main")}
|
||||
className="gap-2"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
@@ -443,6 +445,29 @@ export function CcrRouterManager({ onBack }: CcrRouterManagerProps) {
|
||||
<li>Web UI 管理界面,方便配置和监控</li>
|
||||
<li>无需 Anthropic 账户即可使用 Claude Code</li>
|
||||
</ul>
|
||||
|
||||
{!serviceStatus?.has_ccr_binary && (
|
||||
<div className="mt-4 p-3 bg-yellow-50 dark:bg-yellow-900/20 rounded-lg border border-yellow-200 dark:border-yellow-800">
|
||||
<p className="text-sm font-medium text-yellow-800 dark:text-yellow-200 mb-2">
|
||||
安装说明:
|
||||
</p>
|
||||
<code className="block p-2 bg-black/5 dark:bg-white/5 rounded text-xs">
|
||||
npm install -g @musistudio/claude-code-router
|
||||
</code>
|
||||
<p className="text-xs mt-2 text-muted-foreground">
|
||||
或访问 <a
|
||||
href="#"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
open("https://github.com/musistudio/claude-code-router/tree/main");
|
||||
}}
|
||||
className="text-blue-600 hover:underline"
|
||||
>
|
||||
GitHub 仓库
|
||||
</a> 了解更多安装方式
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</motion.div>
|
||||
|
@@ -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>
|
||||
|
@@ -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,53 @@ 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: "🚌 直连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)" }
|
||||
];
|
||||
|
||||
await performSpeedTest(busNodes, (bestNode) => {
|
||||
finalApiUrl = bestNode.url;
|
||||
setPackycodeNode(bestNode.url);
|
||||
});
|
||||
} else if (packycodeService === 'taxi') {
|
||||
// 滴滴车自动选择
|
||||
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)" }
|
||||
];
|
||||
|
||||
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);
|
||||
@@ -1718,7 +1751,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 +1763,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 +1916,158 @@ 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: "🚌 直连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)" }
|
||||
];
|
||||
|
||||
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: "🚗 直连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)" }
|
||||
];
|
||||
|
||||
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);
|
||||
@@ -2168,6 +2359,118 @@ 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">
|
||||
🚗 直连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)
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
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)" }
|
||||
];
|
||||
|
||||
// 复制 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
|
||||
|
@@ -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
|
||||
@@ -2686,6 +2709,7 @@ export interface CcrServiceStatus {
|
||||
has_ccr_binary: boolean;
|
||||
ccr_version?: string;
|
||||
process_id?: number;
|
||||
raw_output?: string;
|
||||
}
|
||||
|
||||
export interface CcrServiceInfo {
|
||||
|
@@ -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",
|
||||
|
@@ -494,6 +494,7 @@
|
||||
"importFromClaudeDesktop": "从 Claude Desktop 导入",
|
||||
"importFromClaudeDesktopDescription": "自动导入 Claude Desktop 中的所有 MCP 服务器。安装到用户范围(所有项目可用)。",
|
||||
"importing": "导入中...",
|
||||
"exporting": "导出中...",
|
||||
"importFromJSON": "从 JSON 导入",
|
||||
"importFromJSONDescription": "从 JSON 文件导入服务器配置",
|
||||
"chooseJSONFile": "选择 JSON 文件",
|
||||
|
Reference in New Issue
Block a user