lib.rs 6.9 KB

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