lib.rs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. use std::{
  2. net::{SocketAddr, TcpListener},
  3. process::Command,
  4. sync::{Arc, Mutex},
  5. time::{Duration, Instant},
  6. };
  7. use tauri::{AppHandle, LogicalSize, Manager, Monitor, RunEvent, WebviewUrl, WebviewWindow};
  8. use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogResult};
  9. use tauri_plugin_shell::process::{CommandChild, CommandEvent};
  10. use tauri_plugin_shell::ShellExt;
  11. use tokio::net::TcpSocket;
  12. #[derive(Clone)]
  13. struct ServerState(Arc<Mutex<Option<CommandChild>>>);
  14. fn get_sidecar_port() -> u16 {
  15. option_env!("OPENCODE_PORT")
  16. .map(|s| s.to_string())
  17. .or_else(|| std::env::var("OPENCODE_PORT").ok())
  18. .and_then(|port_str| port_str.parse().ok())
  19. .unwrap_or_else(|| {
  20. TcpListener::bind("127.0.0.1:0")
  21. .expect("Failed to bind to find free port")
  22. .local_addr()
  23. .expect("Failed to get local address")
  24. .port()
  25. })
  26. }
  27. fn find_and_kill_process_on_port(port: u16) -> Result<(), Box<dyn std::error::Error>> {
  28. // Find all listeners on the specified port
  29. let listeners = listeners::get_processes_by_port(port)?;
  30. if listeners.is_empty() {
  31. println!("No processes found listening on port {}", port);
  32. return Ok(());
  33. }
  34. for listener in listeners {
  35. let pid = listener.pid;
  36. println!("Found process {} listening on port {}", pid, port);
  37. // Kill the process using platform-appropriate command
  38. #[cfg(target_os = "windows")]
  39. {
  40. Command::new("taskkill")
  41. .args(["/F", "/PID", &pid.to_string()])
  42. .output()?;
  43. }
  44. #[cfg(not(target_os = "windows"))]
  45. {
  46. Command::new("kill")
  47. .args(["-9", &pid.to_string()])
  48. .output()?;
  49. }
  50. println!("Killed process {}", pid);
  51. }
  52. Ok(())
  53. }
  54. fn spawn_sidecar(app: &AppHandle, port: u16) -> CommandChild {
  55. let (mut rx, child) = app
  56. .shell()
  57. .sidecar("opencode")
  58. .unwrap()
  59. .env("OPENCODE_EXPERIMENTAL_ICON_DISCOVERY", "true")
  60. .env("OPENCODE_CLIENT", "desktop")
  61. .args(["serve", &format!("--port={port}")])
  62. .spawn()
  63. .expect("Failed to spawn opencode");
  64. tauri::async_runtime::spawn(async move {
  65. while let Some(event) = rx.recv().await {
  66. match event {
  67. CommandEvent::Stdout(line_bytes) => {
  68. let line = String::from_utf8_lossy(&line_bytes);
  69. print!("{line}");
  70. }
  71. CommandEvent::Stderr(line_bytes) => {
  72. let line = String::from_utf8_lossy(&line_bytes);
  73. eprint!("{line}");
  74. }
  75. _ => {}
  76. }
  77. }
  78. });
  79. child
  80. }
  81. async fn is_server_running(port: u16) -> bool {
  82. TcpSocket::new_v4()
  83. .unwrap()
  84. .connect(SocketAddr::new(
  85. "127.0.0.1".parse().expect("Failed to parse IP"),
  86. port,
  87. ))
  88. .await
  89. .is_ok()
  90. }
  91. #[cfg_attr(mobile, tauri::mobile_entry_point)]
  92. pub fn run() {
  93. let updater_enabled = option_env!("TAURI_SIGNING_PRIVATE_KEY").is_some();
  94. let mut builder = tauri::Builder::default()
  95. .plugin(tauri_plugin_window_state::Builder::new().build())
  96. .plugin(tauri_plugin_store::Builder::new().build())
  97. .plugin(tauri_plugin_dialog::init())
  98. .plugin(tauri_plugin_shell::init())
  99. .plugin(tauri_plugin_process::init())
  100. .plugin(tauri_plugin_opener::init())
  101. .setup(move |app| {
  102. let app = app.handle().clone();
  103. tauri::async_runtime::spawn(async move {
  104. let port = get_sidecar_port();
  105. let should_spawn_sidecar = !is_server_running(port).await;
  106. // if server_running {
  107. // let res = app
  108. // .dialog()
  109. // .message(
  110. // "OpenCode Server is already running, would you like to restart it?",
  111. // )
  112. // .buttons(MessageDialogButtons::YesNo)
  113. // .blocking_show_with_result();
  114. // match res {
  115. // MessageDialogResult::Yes => {
  116. // if let Err(e) = find_and_kill_process_on_port(port) {
  117. // eprintln!("Failed to kill process on port {}: {}", port, e);
  118. // }
  119. // true
  120. // }
  121. // _ => false,
  122. // }
  123. // } else {
  124. // true
  125. // };
  126. let child = if should_spawn_sidecar {
  127. let child = spawn_sidecar(&app, port);
  128. let timestamp = Instant::now();
  129. loop {
  130. if timestamp.elapsed() > Duration::from_secs(7) {
  131. todo!("Handle server spawn timeout");
  132. }
  133. tokio::time::sleep(Duration::from_millis(10)).await;
  134. if is_server_running(port).await {
  135. // give the server a little bit more time to warm up
  136. tokio::time::sleep(Duration::from_millis(10)).await;
  137. break;
  138. }
  139. }
  140. println!("Server ready after {:?}", timestamp.elapsed());
  141. Some(child)
  142. } else {
  143. None
  144. };
  145. let primary_monitor = app.primary_monitor().ok().flatten();
  146. let size = primary_monitor
  147. .map(|m| m.size().to_logical(m.scale_factor()))
  148. .unwrap_or(LogicalSize::new(1920, 1080));
  149. let mut window_builder =
  150. WebviewWindow::builder(&app, "main", WebviewUrl::App("/".into()))
  151. .title("OpenCode")
  152. .inner_size(size.width as f64, size.height as f64)
  153. .decorations(true)
  154. .zoom_hotkeys_enabled(true)
  155. .initialization_script(format!(
  156. r#"
  157. window.__OPENCODE__ ??= {{}};
  158. window.__OPENCODE__.updaterEnabled = {updater_enabled};
  159. window.__OPENCODE__.port = {port};
  160. "#
  161. ));
  162. #[cfg(target_os = "macos")]
  163. {
  164. window_builder = window_builder.hidden_title(true);
  165. }
  166. window_builder.build().expect("Failed to create window");
  167. app.manage(ServerState(Arc::new(Mutex::new(child))));
  168. });
  169. Ok(())
  170. });
  171. if updater_enabled {
  172. builder = builder.plugin(tauri_plugin_updater::Builder::new().build());
  173. }
  174. builder
  175. .build(tauri::generate_context!())
  176. .expect("error while running tauri application")
  177. .run(|app, event| {
  178. if let RunEvent::Exit = event {
  179. println!("Received Exit");
  180. let Some(server_state) = app.try_state::<ServerState>() else {
  181. println!("Server not running");
  182. return;
  183. };
  184. let Some(server_state) = server_state
  185. .0
  186. .lock()
  187. .expect("Failed to acquire mutex lock")
  188. .take()
  189. else {
  190. println!("Server state missing");
  191. return;
  192. };
  193. let _ = server_state.kill();
  194. println!("Killed server");
  195. }
  196. });
  197. }