Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 12 additions & 24 deletions tidewave-core/src/acp_proxy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ Because of this, we don't use the ACP SDK in the browser, but instead handle raw
JSON-RPC messages and use the ACP-SDK for types. The proxy will continue to forward
any requests to the new connection.
*/
use crate::command::create_shell_command;
use anyhow::{anyhow, Result};
use axum::{
extract::{
Expand All @@ -152,7 +153,6 @@ use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use std::{
collections::HashMap,
path::Path,
process::Stdio,
sync::{
atomic::{AtomicBool, AtomicU64, Ordering},
Expand All @@ -161,7 +161,7 @@ use std::{
};
use tokio::{
io::{AsyncBufReadExt, AsyncWriteExt, BufReader},
process::{Child, Command},
process::Child,
sync::{mpsc, Mutex, RwLock},
};
use tracing::{debug, error, info, trace, warn};
Expand Down Expand Up @@ -239,6 +239,8 @@ pub struct TidewaveSpawnOptions {
pub command: String,
pub env: HashMap<String, String>,
pub cwd: String,
#[serde(default)]
is_wsl: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
Expand Down Expand Up @@ -1201,18 +1203,6 @@ async fn forward_response_to_process(
Ok(())
}

fn get_shell_command(cmd: &str) -> (&'static str, Vec<&str>) {
#[cfg(target_os = "windows")]
{
("cmd.exe", vec!["/s", "/c", cmd])
}

#[cfg(not(target_os = "windows"))]
{
("sh", vec!["-c", cmd])
}
}

// ============================================================================
// Process Management
// ============================================================================
Expand All @@ -1221,21 +1211,19 @@ fn get_shell_command(cmd: &str) -> (&'static str, Vec<&str>) {
pub fn real_process_starter() -> ProcessStarterFn {
Arc::new(|spawn_opts: TidewaveSpawnOptions| {
Box::pin(async move {
let (cmd, args) = get_shell_command(&spawn_opts.command);
info!("Starting ACP process: {}", spawn_opts.command);

info!("Starting ACP process: {} with args: {:?}", cmd, args);
let mut cmd = create_shell_command(
&spawn_opts.command,
spawn_opts.env,
&spawn_opts.cwd,
spawn_opts.is_wsl,
);

let mut cmd = Command::new(cmd);
cmd.args(args)
.envs(spawn_opts.env)
.current_dir(Path::new(&spawn_opts.cwd))
.stdin(Stdio::piped())
cmd.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());

#[cfg(windows)]
cmd.creation_flags(winapi::um::winbase::CREATE_NO_WINDOW);

let mut child = cmd
.spawn()
.map_err(|e| anyhow!("Failed to spawn process: {}", e))?;
Expand Down
63 changes: 63 additions & 0 deletions tidewave-core/src/command.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
use std::collections::HashMap;
use std::path::Path;
use tokio::process::Command;

pub fn create_shell_command(
cmd: &str,
env: HashMap<String, String>,
cwd: &str,
#[cfg_attr(not(target_os = "windows"), allow(unused_variables))] is_wsl: bool,
) -> Command {
#[cfg(target_os = "windows")]
{
if is_wsl {
// WSL case: use --cd flag and construct env string
// Build env assignments string: VAR1=value1 VAR2=value2 ... command
let env_string: Vec<String> = env
.iter()
.map(|(k, v)| {
// Escape single quotes in the value by replacing ' with '\''
let escaped_value = v.replace("'", "'\\''");
format!("{}='{}'", k, escaped_value)
})
.collect();

let full_command = if env_string.is_empty() {
cmd.to_string()
} else {
format!("{} {}", env_string.join(" "), cmd)
};

let mut command = Command::new("wsl.exe");
command
.arg("--cd")
.arg(cwd)
.arg("sh")
.arg("-c")
.arg(full_command);
cmd.creation_flags(winapi::um::winbase::CREATE_NO_WINDOW)
} else {
// Windows cmd case: use .current_dir()
let mut command = Command::new("cmd.exe");
command
.arg("/s")
.arg("/c")
.arg(cmd)
.envs(env)
.current_dir(Path::new(cwd));
cmd.creation_flags(winapi::um::winbase::CREATE_NO_WINDOW)
}
}

#[cfg(not(target_os = "windows"))]
{
// Unix case: use .current_dir()
let mut command = Command::new("sh");
command
.arg("-c")
.arg(cmd)
.envs(env)
.current_dir(Path::new(cwd));
command
}
}
1 change: 1 addition & 0 deletions tidewave-core/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
pub mod acp_proxy;
mod command;
pub mod config;
mod mcp_remote;
pub mod server;
Expand Down
150 changes: 125 additions & 25 deletions tidewave-core/src/server.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::command::create_shell_command;
use crate::config::Config;
use axum::{
body::{Body, Bytes},
Expand All @@ -18,7 +19,7 @@ use std::env;
use std::path::Path;
use std::process::Stdio;
use std::time::UNIX_EPOCH;
use tokio::{io::AsyncReadExt, net::TcpListener, process::Command};
use tokio::{io::AsyncReadExt, net::TcpListener};
use tracing::{debug, error, info};
use which;

Expand All @@ -32,22 +33,34 @@ struct ShellParams {
command: String,
cwd: Option<String>,
env: Option<HashMap<String, String>>,
#[serde(default)]
#[allow(dead_code)]
is_wsl: bool,
}

#[derive(Deserialize)]
struct StatFileParams {
path: String,
#[serde(default)]
#[allow(dead_code)]
is_wsl: bool,
}

#[derive(Deserialize)]
struct ReadFileParams {
path: String,
#[serde(default)]
#[allow(dead_code)]
is_wsl: bool,
}

#[derive(Deserialize)]
struct WriteFileParams {
path: String,
content: String,
#[serde(default)]
#[allow(dead_code)]
is_wsl: bool,
}

#[derive(Deserialize)]
Expand All @@ -56,6 +69,9 @@ struct WhichParams {
// Note that cwd is only used in case PATH in env is also set
cwd: Option<String>,
env: Option<HashMap<String, String>>,
#[serde(default)]
#[allow(dead_code)]
is_wsl: bool,
}

#[derive(Serialize)]
Expand Down Expand Up @@ -290,20 +306,11 @@ async fn verify_origin(
}

async fn shell_handler(Json(payload): Json<ShellParams>) -> Result<Response<Body>, StatusCode> {
let (cmd, args) = get_shell_command(&payload.command);
let cwd = payload.cwd.unwrap_or(".".to_string());
let env = payload.env.unwrap_or_else(|| std::env::vars().collect());

let mut command = Command::new(cmd);
command
.args(args)
.envs(env)
.current_dir(Path::new(&cwd))
.stdout(Stdio::piped())
.stderr(Stdio::piped());

#[cfg(windows)]
command.creation_flags(winapi::um::winbase::CREATE_NO_WINDOW);
let mut command = create_shell_command(&payload.command, env, &cwd, payload.is_wsl);
command.stdout(Stdio::piped()).stderr(Stdio::piped());

let mut child = command
.spawn()
Expand Down Expand Up @@ -377,32 +384,60 @@ fn create_status_chunk(status: i32) -> Bytes {
chunk.freeze()
}

fn get_shell_command(cmd: &str) -> (&'static str, Vec<&str>) {
#[cfg(target_os = "windows")]
{
("cmd.exe", vec!["/s", "/c", cmd])
}
#[cfg(target_os = "windows")]
async fn wslpath_to_windows(wsl_path: &str) -> Result<String, String> {
let mut command = Command::new("wsl.exe");
command
.arg("wslpath")
.arg("-w")
.arg(wsl_path)
.stdout(Stdio::piped())
.stderr(Stdio::piped());

#[cfg(not(target_os = "windows"))]
{
("sh", vec!["-c", cmd])
let output = command
.output()
.await
.map_err(|e| format!("Failed to run wslpath: {}", e))?;

if output.status.success() {
let path = String::from_utf8_lossy(&output.stdout).trim().to_string();
Ok(path)
} else {
let error = String::from_utf8_lossy(&output.stderr).trim().to_string();
Err(format!("wslpath failed: {}", error))
}
}

async fn read_file_handler(
Json(payload): Json<ReadFileParams>,
) -> Result<Json<ReadFileResponse>, StatusCode> {
let path = Path::new(&payload.path);
#[cfg(target_os = "windows")]
if payload.is_wsl {
match wslpath_to_windows(&payload.path).await {
Ok(windows_path) => windows_path,
Err(error) => {
return Ok(Json(ReadFileResponse::ReadFileResponseErr {
success: false,
error,
}));
}
}
} else {
payload.path.clone()
};

if !path.is_absolute() {
#[cfg(not(target_os = "windows"))]
let file_path = payload.path.clone();

if !Path::new(&file_path).is_absolute() {
return Err(StatusCode::BAD_REQUEST);
}

let result = async {
let content = tokio::fs::read_to_string(&payload.path)
let content = tokio::fs::read_to_string(&file_path)
.await
.map_err(|e| e.kind().to_string())?;
let mtime = fetch_mtime(payload.path)?;
let mtime = fetch_mtime(file_path)?;
Ok::<_, String>((content, mtime))
}
.await;
Expand All @@ -429,7 +464,24 @@ async fn write_file_handler(
return Err(StatusCode::BAD_REQUEST);
}

#[cfg(target_os = "windows")]
let path_str = if payload.is_wsl {
match wslpath_to_windows(&payload.path).await {
Ok(windows_path) => windows_path,
Err(error) => {
return Ok(Json(WriteFileResponse::WriteFileResponseErr {
success: false,
error,
}));
}
}
} else {
payload.path.clone()
};

#[cfg(not(target_os = "windows"))]
let path_str = payload.path.clone();

let content = payload.content.clone();
let bytes_written = content.len();

Expand Down Expand Up @@ -474,7 +526,25 @@ async fn stat_file_handler(
return Err(StatusCode::BAD_REQUEST);
}

let mtime_op = fetch_mtime(query.path);
#[cfg(target_os = "windows")]
let file_path = if query.is_wsl {
match wslpath_to_windows(&query.path).await {
Ok(windows_path) => windows_path,
Err(error) => {
return Ok(Json(StatFileResponse::StatFileResponseErr {
success: false,
error,
}));
}
}
} else {
query.path.clone()
};

#[cfg(not(target_os = "windows"))]
let file_path = query.path.clone();

let mtime_op = fetch_mtime(file_path);

match mtime_op {
Ok(mtime) => Ok(Json(StatFileResponse::StatFileResponseOk {
Expand All @@ -499,6 +569,36 @@ fn fetch_mtime(path: String) -> Result<u64, String> {
}

async fn which_handler(Json(params): Json<WhichParams>) -> Result<Json<WhichResponse>, StatusCode> {
#[cfg(target_os = "windows")]
{
// Check if we're in WSL context
if let Some(env) = &params.env {
if env.get("WSL_DISTRO_NAME").is_some() {
// Run which command inside WSL
let cwd = params.cwd.as_deref().unwrap_or(".");
let env_clone = env.clone();
let command_str = format!("which {}", params.command);

let mut command = create_shell_command(&command_str, env_clone, cwd, params.is_wsl);
command.stdout(Stdio::piped()).stderr(Stdio::piped());

let output = command
.output()
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

if output.status.success() {
let path = String::from_utf8_lossy(&output.stdout).trim().to_string();
if !path.is_empty() {
return Ok(Json(WhichResponse { path: Some(path) }));
}
}
return Ok(Json(WhichResponse { path: None }));
}
}
}

// Non-WSL case: use the which crate
let result = if let Some(env) = params.env {
if let Some(paths) = env.get("PATH") {
let paths = paths.clone();
Expand Down
Loading