4 Commits

Author SHA1 Message Date
50cce7a22c 删除冗余导入,优化代码结构 2025-09-07 23:23:18 +08:00
027999a9e5 适配windows 2025-09-07 23:11:49 +08:00
74e85fb8a2 适配windows 2025-09-06 20:53:39 +08:00
79d66a69a3 适配windows 2025-09-06 20:53:05 +08:00
7 changed files with 231 additions and 86 deletions

BIN
src-tauri/icons/icon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

View File

@@ -48,10 +48,37 @@ pub fn find_claude_binary(app_handle: &tauri::AppHandle) -> Result<String, Strin
) {
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);
}
@@ -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;
}
// Process each line (Windows 'where' can return multiple paths)
for line in output_str.lines() {
let mut path = line.trim().to_string();
if path.is_empty() {
continue;
}
// 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())
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 {
Some(output_str)
}?;
continue;
}
}
debug!("'which' found claude at: {}", path);
// 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(&path).exists() {
warn!("Path from 'which' does not exist: {}", path);
return None;
if !PathBuf::from(&final_path).exists() {
warn!("Path from '{}' does not exist: {}", command_name, final_path);
continue;
}
// Get version
let version = get_claude_version(&path).ok().flatten();
let version = get_claude_version(&final_path).ok().flatten();
Some(ClaudeInstallation {
path,
installations.push(ClaudeInstallation {
path: final_path,
version,
source: "which".to_string(),
source: command_name.to_string(),
installation_type: InstallationType::System,
})
});
}
_ => None,
}
_ => {}
}
installations
}
/// Find Claude installations in NVM directories

View File

@@ -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
// 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
// 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") {
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

View File

@@ -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@2x.png",
"icons/icon.icns"
"icons/icon.icns",
"icons/icon.png"
],
"resources": [],
"externalBin": [],

View File

@@ -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 ? (
// 文件编辑器视图
<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

View File

@@ -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,

View File

@@ -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'],
},
},
},