Compare commits
6 Commits
Author | SHA1 | Date | |
---|---|---|---|
6ef45f328c | |||
0e78b08549 | |||
50cce7a22c | |||
027999a9e5 | |||
74e85fb8a2 | |||
79d66a69a3 |
@@ -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"
|
||||
|
BIN
src-tauri/icons/icon.ico
Normal file
BIN
src-tauri/icons/icon.ico
Normal file
Binary file not shown.
After Width: | Height: | Size: 32 KiB |
@@ -47,23 +47,50 @@ pub fn find_claude_binary(app_handle: &tauri::AppHandle) -> Result<String, Strin
|
||||
|row| row.get::<_, String>(0),
|
||||
) {
|
||||
info!("Found stored claude path in database: {}", stored_path);
|
||||
|
||||
// Check if the path still exists
|
||||
|
||||
// Check if the path still exists and works
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
let final_path = stored_path.clone();
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
let path_buf = PathBuf::from(&stored_path);
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
let mut final_path = stored_path.clone();
|
||||
#[cfg(target_os = "windows")]
|
||||
let mut path_buf = PathBuf::from(&stored_path);
|
||||
|
||||
// On Windows, if stored path exists but is not executable (shell script), try .cmd version
|
||||
#[cfg(target_os = "windows")]
|
||||
if path_buf.exists() && !stored_path.ends_with(".cmd") && !stored_path.ends_with(".exe") {
|
||||
// Test if the current path works by trying to get version
|
||||
if let Err(_) = get_claude_version(&stored_path) {
|
||||
// If it fails, try the .cmd version
|
||||
let cmd_path = format!("{}.cmd", stored_path);
|
||||
let cmd_path_buf = PathBuf::from(&cmd_path);
|
||||
if cmd_path_buf.exists() {
|
||||
if let Ok(_) = get_claude_version(&cmd_path) {
|
||||
final_path = cmd_path;
|
||||
path_buf = cmd_path_buf;
|
||||
info!("Using .cmd version instead of shell script: {}", final_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if path_buf.exists() && path_buf.is_file() {
|
||||
return Ok(stored_path);
|
||||
return Ok(final_path);
|
||||
} else {
|
||||
warn!("Stored claude path no longer exists: {}", stored_path);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Check user preference
|
||||
let preference = conn.query_row(
|
||||
"SELECT value FROM app_settings WHERE key = 'claude_installation_preference'",
|
||||
[],
|
||||
|row| row.get::<_, String>(0),
|
||||
).unwrap_or_else(|_| "system".to_string());
|
||||
|
||||
|
||||
info!("User preference for Claude installation: {}", preference);
|
||||
}
|
||||
}
|
||||
@@ -146,10 +173,8 @@ fn source_preference(installation: &ClaudeInstallation) -> u8 {
|
||||
fn discover_system_installations() -> Vec<ClaudeInstallation> {
|
||||
let mut installations = Vec::new();
|
||||
|
||||
// 1. Try 'which' command first (now works in production)
|
||||
if let Some(installation) = try_which_command() {
|
||||
installations.push(installation);
|
||||
}
|
||||
// 1. Try system command first (now works in production and can return multiple installations)
|
||||
installations.extend(find_which_installations());
|
||||
|
||||
// 2. Check NVM paths
|
||||
installations.extend(find_nvm_installations());
|
||||
@@ -164,48 +189,111 @@ fn discover_system_installations() -> Vec<ClaudeInstallation> {
|
||||
installations
|
||||
}
|
||||
|
||||
/// Try using the 'which' command to find Claude
|
||||
fn try_which_command() -> Option<ClaudeInstallation> {
|
||||
debug!("Trying 'which claude' to find binary...");
|
||||
/// Try using the command to find Claude installations
|
||||
/// Returns multiple installations if found (Windows 'where' can return multiple paths)
|
||||
fn find_which_installations() -> Vec<ClaudeInstallation> {
|
||||
debug!("Trying to find claude binary...");
|
||||
|
||||
match Command::new("which").arg("claude").output() {
|
||||
// Use 'where' on Windows, 'which' on Unix
|
||||
#[cfg(target_os = "windows")]
|
||||
let command_name = "where";
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
let command_name = "which";
|
||||
|
||||
let mut installations = Vec::new();
|
||||
|
||||
match Command::new(command_name).arg("claude").output() {
|
||||
Ok(output) if output.status.success() => {
|
||||
let output_str = String::from_utf8_lossy(&output.stdout).trim().to_string();
|
||||
|
||||
if output_str.is_empty() {
|
||||
return None;
|
||||
return installations;
|
||||
}
|
||||
|
||||
// Parse aliased output: "claude: aliased to /path/to/claude"
|
||||
let path = if output_str.starts_with("claude:") && output_str.contains("aliased to") {
|
||||
output_str
|
||||
.split("aliased to")
|
||||
.nth(1)
|
||||
.map(|s| s.trim().to_string())
|
||||
} else {
|
||||
Some(output_str)
|
||||
}?;
|
||||
// Process each line (Windows 'where' can return multiple paths)
|
||||
for line in output_str.lines() {
|
||||
let mut path = line.trim().to_string();
|
||||
|
||||
debug!("'which' found claude at: {}", path);
|
||||
if path.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Verify the path exists
|
||||
if !PathBuf::from(&path).exists() {
|
||||
warn!("Path from 'which' does not exist: {}", path);
|
||||
return None;
|
||||
// Parse aliased output: "claude: aliased to /path/to/claude"
|
||||
if path.starts_with("claude:") && path.contains("aliased to") {
|
||||
if let Some(aliased_path) = path.split("aliased to").nth(1) {
|
||||
path = aliased_path.trim().to_string();
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Convert Unix-style path to Windows path if needed
|
||||
#[cfg(target_os = "windows")]
|
||||
let path = {
|
||||
if path.starts_with("/c/") {
|
||||
// Convert /c/path to C:\path
|
||||
let windows_path = path.replace("/c/", "C:\\").replace("/", "\\");
|
||||
windows_path
|
||||
} else if path.starts_with("/") && path.len() > 3 && path.chars().nth(2) == Some('/') {
|
||||
// Convert /X/path to X:\path where X is drive letter
|
||||
let drive = path.chars().nth(1).unwrap();
|
||||
let rest = &path[3..];
|
||||
format!("{}:\\{}", drive.to_uppercase(), rest.replace("/", "\\"))
|
||||
} else {
|
||||
path
|
||||
}
|
||||
};
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
let path = path;
|
||||
|
||||
debug!("'{}' found claude at: {}", command_name, path);
|
||||
|
||||
// On Windows, prefer .cmd files over shell scripts
|
||||
#[cfg(target_os = "windows")]
|
||||
let final_path = {
|
||||
if !path.ends_with(".cmd") && !path.ends_with(".exe") {
|
||||
// Check if there's a .cmd file alongside
|
||||
let cmd_path = format!("{}.cmd", path);
|
||||
if PathBuf::from(&cmd_path).exists() {
|
||||
// Only use .cmd if the original doesn't work
|
||||
if let Err(_) = get_claude_version(&path) {
|
||||
cmd_path
|
||||
} else {
|
||||
path
|
||||
}
|
||||
} else {
|
||||
path
|
||||
}
|
||||
} else {
|
||||
path
|
||||
}
|
||||
};
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
let final_path = path;
|
||||
|
||||
// Verify the path exists
|
||||
if !PathBuf::from(&final_path).exists() {
|
||||
warn!("Path from '{}' does not exist: {}", command_name, final_path);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Get version
|
||||
let version = get_claude_version(&final_path).ok().flatten();
|
||||
|
||||
installations.push(ClaudeInstallation {
|
||||
path: final_path,
|
||||
version,
|
||||
source: command_name.to_string(),
|
||||
installation_type: InstallationType::System,
|
||||
});
|
||||
}
|
||||
|
||||
// Get version
|
||||
let version = get_claude_version(&path).ok().flatten();
|
||||
|
||||
Some(ClaudeInstallation {
|
||||
path,
|
||||
version,
|
||||
source: "which".to_string(),
|
||||
installation_type: InstallationType::System,
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
_ => {}
|
||||
}
|
||||
|
||||
installations
|
||||
}
|
||||
|
||||
/// Find Claude installations in NVM directories
|
||||
@@ -364,10 +452,10 @@ fn get_claude_version(path: &str) -> Result<Option<String>, String> {
|
||||
/// Extract version string from command output
|
||||
fn extract_version_from_output(stdout: &[u8]) -> Option<String> {
|
||||
let output_str = String::from_utf8_lossy(stdout);
|
||||
|
||||
|
||||
// Debug log the raw output
|
||||
debug!("Raw version output: {:?}", output_str);
|
||||
|
||||
|
||||
// Use regex to directly extract version pattern (e.g., "1.0.41")
|
||||
// This pattern matches:
|
||||
// - One or more digits, followed by
|
||||
@@ -377,7 +465,7 @@ fn extract_version_from_output(stdout: &[u8]) -> Option<String> {
|
||||
// - One or more digits
|
||||
// - Optionally followed by pre-release/build metadata
|
||||
let version_regex = regex::Regex::new(r"(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?(?:\+[a-zA-Z0-9.-]+)?)").ok()?;
|
||||
|
||||
|
||||
if let Some(captures) = version_regex.captures(&output_str) {
|
||||
if let Some(version_match) = captures.get(1) {
|
||||
let version = version_match.as_str().to_string();
|
||||
@@ -385,7 +473,7 @@ fn extract_version_from_output(stdout: &[u8]) -> Option<String> {
|
||||
return Some(version);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
debug!("No version found in output");
|
||||
None
|
||||
}
|
||||
@@ -465,7 +553,7 @@ fn compare_versions(a: &str, b: &str) -> Ordering {
|
||||
/// This ensures commands like Claude can find Node.js and other dependencies
|
||||
pub fn create_command_with_env(program: &str) -> Command {
|
||||
let mut cmd = Command::new(program);
|
||||
|
||||
|
||||
info!("Creating command for: {}", program);
|
||||
|
||||
// Inherit essential environment variables from parent process
|
||||
@@ -493,7 +581,7 @@ pub fn create_command_with_env(program: &str) -> Command {
|
||||
cmd.env(&key, &value);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Log proxy-related environment variables for debugging
|
||||
info!("Command will use proxy settings:");
|
||||
if let Ok(http_proxy) = std::env::var("HTTP_PROXY") {
|
||||
|
@@ -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,35 +26,128 @@ pub struct CcrServiceInfo {
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// 检查 CCR 是否已安装
|
||||
#[tauri::command]
|
||||
pub async fn check_ccr_installation() -> Result<bool, String> {
|
||||
// 直接尝试执行 ccr --version 命令来检测是否安装
|
||||
// 这比使用 which 命令更可靠,特别是在打包后的应用中
|
||||
let output = Command::new("ccr")
|
||||
.arg("--version")
|
||||
/// 获取可能的 CCR 路径列表
|
||||
fn get_possible_ccr_paths() -> Vec<String> {
|
||||
let mut paths = vec!["ccr".to_string()]; // PATH 中的 ccr
|
||||
|
||||
// 获取用户主目录
|
||||
let home = std::env::var("HOME").or_else(|_| std::env::var("USERPROFILE")).unwrap_or_default();
|
||||
|
||||
#[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(),
|
||||
]);
|
||||
}
|
||||
|
||||
#[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));
|
||||
|
||||
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),
|
||||
]);
|
||||
}
|
||||
|
||||
#[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(),
|
||||
]);
|
||||
}
|
||||
|
||||
paths
|
||||
}
|
||||
|
||||
/// 查找实际的 CCR 路径
|
||||
fn find_ccr_path() -> Option<String> {
|
||||
// 先检查缓存
|
||||
if let Ok(cached) = CCR_PATH.lock() {
|
||||
if cached.is_some() {
|
||||
return cached.clone();
|
||||
}
|
||||
}
|
||||
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// 测试给定路径的 CCR 命令是否可用
|
||||
fn test_ccr_command(path: &str) -> bool {
|
||||
let output = Command::new(path)
|
||||
.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)
|
||||
}
|
||||
}
|
||||
matches!(output, Ok(result) if result.status.success())
|
||||
}
|
||||
/// 检查 CCR 是否已安装
|
||||
#[tauri::command]
|
||||
pub async fn check_ccr_installation() -> Result<bool, String> {
|
||||
Ok(find_ccr_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")
|
||||
let output = Command::new(&ccr_path)
|
||||
.arg(arg)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
@@ -81,19 +182,31 @@ pub async fn get_ccr_service_status() -> Result<CcrServiceStatus, String> {
|
||||
has_ccr_binary: false,
|
||||
ccr_version: None,
|
||||
process_id: None,
|
||||
raw_output: None,
|
||||
});
|
||||
}
|
||||
|
||||
// 获取版本信息
|
||||
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 = Command::new(&ccr_path);
|
||||
cmd.arg("status")
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped());
|
||||
|
||||
// 继承环境变量
|
||||
cmd.env_clear();
|
||||
for (key, value) in std::env::vars() {
|
||||
cmd.env(key, value);
|
||||
}
|
||||
|
||||
info!("Executing ccr status command");
|
||||
let output = cmd.output();
|
||||
|
||||
let output = match output {
|
||||
Ok(o) => o,
|
||||
@@ -106,6 +219,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 +227,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 +257,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 +279,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 +290,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 +299,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 +329,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 +359,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 +371,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,7 +384,7 @@ pub async fn start_ccr_service() -> Result<CcrServiceInfo, String> {
|
||||
}
|
||||
|
||||
// 启动服务
|
||||
let _output = Command::new("ccr")
|
||||
let _output = Command::new(&ccr_path)
|
||||
.arg("start")
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
@@ -250,7 +414,10 @@ 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")
|
||||
.output()
|
||||
.map_err(|e| format!("Failed to stop ccr service: {}", e))?;
|
||||
@@ -276,7 +443,10 @@ 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")
|
||||
.output()
|
||||
.map_err(|e| format!("Failed to restart ccr service: {}", e))?;
|
||||
@@ -314,8 +484,11 @@ 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")
|
||||
.spawn()
|
||||
.map_err(|e| format!("Failed to open ccr ui: {}", e))?;
|
||||
|
@@ -5,7 +5,7 @@ use tauri::{AppHandle, Emitter, State};
|
||||
use tokio::sync::Mutex;
|
||||
use uuid::Uuid;
|
||||
use anyhow::Result;
|
||||
use portable_pty::{native_pty_system, CommandBuilder, PtySize};
|
||||
use portable_pty::{native_pty_system, CommandBuilder, PtySize, Child, MasterPty};
|
||||
use std::io::{Read, Write};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
@@ -19,6 +19,8 @@ pub struct TerminalSession {
|
||||
/// Terminal child process wrapper
|
||||
pub struct TerminalChild {
|
||||
writer: Arc<Mutex<Box<dyn Write + Send>>>,
|
||||
_master: Box<dyn MasterPty + Send>, // Keep master PTY alive
|
||||
_child: Box<dyn Child + Send + Sync>, // Keep child process alive
|
||||
}
|
||||
|
||||
/// State for managing terminal sessions
|
||||
@@ -60,36 +62,69 @@ pub async fn create_terminal_session(
|
||||
|
||||
// Get shell command
|
||||
let shell = get_default_shell();
|
||||
log::info!("Using shell: {}", shell);
|
||||
let mut cmd = CommandBuilder::new(&shell);
|
||||
|
||||
// Set as login interactive shell
|
||||
if shell.contains("bash") || shell.contains("zsh") {
|
||||
cmd.arg("-il"); // Interactive login shell
|
||||
} else if shell.contains("fish") {
|
||||
cmd.arg("-il");
|
||||
// Set shell-specific arguments
|
||||
if cfg!(target_os = "windows") {
|
||||
if shell.contains("pwsh") {
|
||||
// PowerShell Core - stay interactive
|
||||
cmd.arg("-NoLogo");
|
||||
cmd.arg("-NoExit");
|
||||
} else if shell.contains("powershell") {
|
||||
// Windows PowerShell - stay interactive
|
||||
cmd.arg("-NoLogo");
|
||||
cmd.arg("-NoExit");
|
||||
} else {
|
||||
// cmd.exe - use /K to keep session open
|
||||
cmd.arg("/K");
|
||||
}
|
||||
} else {
|
||||
// Unix shells: Set as login interactive shell
|
||||
if shell.contains("bash") || shell.contains("zsh") {
|
||||
cmd.arg("-il"); // Interactive login shell
|
||||
} else if shell.contains("fish") {
|
||||
cmd.arg("-il");
|
||||
}
|
||||
}
|
||||
|
||||
// Set working directory
|
||||
cmd.cwd(working_directory.clone());
|
||||
|
||||
// Set environment variables
|
||||
cmd.env("TERM", "xterm-256color");
|
||||
cmd.env("COLORTERM", "truecolor");
|
||||
cmd.env("LANG", std::env::var("LANG").unwrap_or_else(|_| "en_US.UTF-8".to_string()));
|
||||
cmd.env("LC_ALL", std::env::var("LC_ALL").unwrap_or_else(|_| "en_US.UTF-8".to_string()));
|
||||
cmd.env("LC_CTYPE", std::env::var("LC_CTYPE").unwrap_or_else(|_| "en_US.UTF-8".to_string()));
|
||||
|
||||
// 继承其他环境变量
|
||||
for (key, value) in std::env::vars() {
|
||||
if !key.starts_with("TERM") && !key.starts_with("COLORTERM") && !key.starts_with("LC_") && !key.starts_with("LANG") {
|
||||
cmd.env(&key, &value);
|
||||
// Set environment variables based on platform
|
||||
if cfg!(target_os = "windows") {
|
||||
// Windows-specific environment
|
||||
cmd.env("TERM", "xterm-256color");
|
||||
// Keep PATH and other essential Windows environment variables
|
||||
for (key, value) in std::env::vars() {
|
||||
if !key.starts_with("TAURI_") && !key.starts_with("VITE_") {
|
||||
cmd.env(&key, &value);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Unix-specific environment
|
||||
cmd.env("TERM", "xterm-256color");
|
||||
cmd.env("COLORTERM", "truecolor");
|
||||
cmd.env("LANG", std::env::var("LANG").unwrap_or_else(|_| "en_US.UTF-8".to_string()));
|
||||
cmd.env("LC_ALL", std::env::var("LC_ALL").unwrap_or_else(|_| "en_US.UTF-8".to_string()));
|
||||
cmd.env("LC_CTYPE", std::env::var("LC_CTYPE").unwrap_or_else(|_| "en_US.UTF-8".to_string()));
|
||||
|
||||
// Inherit other Unix environment variables
|
||||
for (key, value) in std::env::vars() {
|
||||
if !key.starts_with("TERM") && !key.starts_with("COLORTERM") &&
|
||||
!key.starts_with("LC_") && !key.starts_with("LANG") &&
|
||||
!key.starts_with("TAURI_") && !key.starts_with("VITE_") {
|
||||
cmd.env(&key, &value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Spawn the shell process
|
||||
let _child = pty_pair.slave.spawn_command(cmd)
|
||||
let child = pty_pair.slave.spawn_command(cmd)
|
||||
.map_err(|e| format!("Failed to spawn shell: {}", e))?;
|
||||
|
||||
log::info!("Shell process spawned successfully for session: {}", session_id);
|
||||
|
||||
// Get writer for stdin
|
||||
let writer = pty_pair.master.take_writer()
|
||||
.map_err(|e| format!("Failed to get PTY writer: {}", e))?;
|
||||
@@ -103,15 +138,20 @@ pub async fn create_terminal_session(
|
||||
// Spawn reader thread
|
||||
std::thread::spawn(move || {
|
||||
let mut buffer = [0u8; 4096];
|
||||
log::info!("PTY reader thread started for session: {}", session_id_clone);
|
||||
loop {
|
||||
match reader.read(&mut buffer) {
|
||||
Ok(0) => break, // EOF
|
||||
Ok(0) => {
|
||||
log::warn!("PTY reader got EOF for session: {}", session_id_clone);
|
||||
break; // EOF
|
||||
}
|
||||
Ok(n) => {
|
||||
let data = String::from_utf8_lossy(&buffer[..n]).to_string();
|
||||
log::debug!("PTY reader got {} bytes for session {}: {:?}", n, session_id_clone, data);
|
||||
let _ = app_handle_clone.emit(&format!("terminal-output:{}", session_id_clone), &data);
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("Error reading PTY output: {}", e);
|
||||
log::error!("Error reading PTY output for session {}: {}", session_id_clone, e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -119,9 +159,11 @@ pub async fn create_terminal_session(
|
||||
log::debug!("PTY reader thread finished for session: {}", session_id_clone);
|
||||
});
|
||||
|
||||
// Store the session with PTY writer
|
||||
// Store the session with PTY writer, master PTY and child process
|
||||
let terminal_child = TerminalChild {
|
||||
writer: Arc::new(Mutex::new(writer)),
|
||||
_master: pty_pair.master,
|
||||
_child: child,
|
||||
};
|
||||
|
||||
{
|
||||
@@ -245,13 +287,13 @@ pub async fn cleanup_terminal_sessions(
|
||||
/// Get the default shell for the current platform
|
||||
fn get_default_shell() -> String {
|
||||
if cfg!(target_os = "windows") {
|
||||
// Try PowerShell first, fallback to cmd
|
||||
// Try PowerShell Core (pwsh) first, then Windows PowerShell, fallback to cmd
|
||||
if std::process::Command::new("pwsh").arg("--version").output().is_ok() {
|
||||
"pwsh".to_string()
|
||||
} else if std::process::Command::new("powershell").arg("-Version").output().is_ok() {
|
||||
"powershell".to_string()
|
||||
} else {
|
||||
"cmd".to_string()
|
||||
"cmd.exe".to_string()
|
||||
}
|
||||
} else {
|
||||
// Unix-like systems: try zsh, bash, then sh
|
||||
|
@@ -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: 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",
|
||||
"assetProtocol": {
|
||||
"enable": true,
|
||||
"scope": [
|
||||
@@ -34,18 +34,13 @@
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"targets": [
|
||||
"deb",
|
||||
"rpm",
|
||||
"appimage",
|
||||
"app",
|
||||
"dmg"
|
||||
],
|
||||
"targets": "all",
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
"icons/128x128.png",
|
||||
"icons/128x128@2x.png",
|
||||
"icons/icon.icns"
|
||||
"icons/icon.icns",
|
||||
"icons/icon.png"
|
||||
],
|
||||
"resources": [],
|
||||
"externalBin": [],
|
||||
|
@@ -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>
|
||||
|
@@ -45,7 +45,8 @@ import { SplitPane } from "@/components/ui/split-pane";
|
||||
import { WebviewPreview } from "./WebviewPreview";
|
||||
import { FileExplorerPanelEnhanced } from "./FileExplorerPanelEnhanced";
|
||||
import { GitPanelEnhanced } from "./GitPanelEnhanced";
|
||||
import { FileEditorEnhanced } from "./FileEditorEnhanced";
|
||||
// 动态导入 FileEditorEnhanced 以减少初始包大小
|
||||
const FileEditorEnhanced = React.lazy(() => import("./FileEditorEnhanced"));
|
||||
import { SlashCommandsManager } from "./SlashCommandsManager";
|
||||
import type { ClaudeStreamMessage } from "./AgentExecution";
|
||||
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||
@@ -1904,11 +1905,17 @@ export const ClaudeCodeSession: React.FC<ClaudeCodeSessionProps> = ({
|
||||
<div className={cn("h-full w-full", layout.activeView === 'terminal' ? 'hidden' : 'block')}>
|
||||
{layout.activeView === 'editor' && layout.editingFile ? (
|
||||
// 文件编辑器视图
|
||||
<FileEditorEnhanced
|
||||
filePath={layout.editingFile}
|
||||
onClose={closeFileEditor}
|
||||
className="h-full"
|
||||
/>
|
||||
<React.Suspense fallback={
|
||||
<div className="flex items-center justify-center h-full">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
|
||||
</div>
|
||||
}>
|
||||
<FileEditorEnhanced
|
||||
filePath={layout.editingFile}
|
||||
onClose={closeFileEditor}
|
||||
className="h-full"
|
||||
/>
|
||||
</React.Suspense>
|
||||
) : layout.activeView === 'preview' && layout.previewUrl ? (
|
||||
// 预览视图
|
||||
<SplitPane
|
||||
|
@@ -2686,6 +2686,7 @@ export interface CcrServiceStatus {
|
||||
has_ccr_binary: boolean;
|
||||
ccr_version?: string;
|
||||
process_id?: number;
|
||||
raw_output?: string;
|
||||
}
|
||||
|
||||
export interface CcrServiceInfo {
|
||||
|
@@ -33,6 +33,12 @@ i18n
|
||||
zh: {
|
||||
common: zh,
|
||||
},
|
||||
'zh-CN': {
|
||||
common: zh,
|
||||
},
|
||||
'zh-TW': {
|
||||
common: zh,
|
||||
},
|
||||
},
|
||||
|
||||
// 命名空间配置
|
||||
@@ -48,7 +54,7 @@ i18n
|
||||
},
|
||||
|
||||
// 白名单支持的语言
|
||||
supportedLngs: ['en', 'zh'],
|
||||
supportedLngs: ['en', 'zh', 'zh-CN', 'zh-TW'],
|
||||
|
||||
// 非显式支持的语言回退到en
|
||||
nonExplicitSupportedLngs: true,
|
||||
|
@@ -51,10 +51,17 @@ export default defineConfig(async () => ({
|
||||
'react-vendor': ['react', 'react-dom'],
|
||||
'ui-vendor': ['@radix-ui/react-dialog', '@radix-ui/react-dropdown-menu', '@radix-ui/react-select', '@radix-ui/react-tabs', '@radix-ui/react-tooltip', '@radix-ui/react-switch', '@radix-ui/react-popover'],
|
||||
'editor-vendor': ['@uiw/react-md-editor'],
|
||||
'monaco-editor': ['monaco-editor', '@monaco-editor/react'],
|
||||
'syntax-vendor': ['react-syntax-highlighter'],
|
||||
// Animation and motion
|
||||
'framer-motion': ['framer-motion'],
|
||||
// Tauri and other utilities
|
||||
'tauri': ['@tauri-apps/api', '@tauri-apps/plugin-dialog', '@tauri-apps/plugin-shell'],
|
||||
'tauri': ['@tauri-apps/api', '@tauri-apps/plugin-dialog', '@tauri-apps/plugin-shell', '@tauri-apps/plugin-fs', '@tauri-apps/plugin-clipboard-manager'],
|
||||
'utils': ['date-fns', 'clsx', 'tailwind-merge'],
|
||||
// Charts and visualization
|
||||
'recharts': ['recharts'],
|
||||
// Virtual scrolling
|
||||
'virtual': ['@tanstack/react-virtual'],
|
||||
},
|
||||
},
|
||||
},
|
||||
|
Reference in New Issue
Block a user