lib.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. mod cli;
  2. mod window_customizer;
  3. use cli::{install_cli, sync_cli};
  4. use futures::FutureExt;
  5. use std::{
  6. collections::VecDeque,
  7. net::TcpListener,
  8. sync::{Arc, Mutex},
  9. time::{Duration, Instant},
  10. };
  11. use tauri::{AppHandle, LogicalSize, Manager, RunEvent, State, WebviewUrl, WebviewWindow};
  12. use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogResult};
  13. use tauri_plugin_shell::process::{CommandChild, CommandEvent};
  14. use tauri_plugin_store::StoreExt;
  15. use crate::window_customizer::PinchZoomDisablePlugin;
  16. const SETTINGS_STORE: &str = "opencode.settings.dat";
  17. const DEFAULT_SERVER_URL_KEY: &str = "defaultServerUrl";
  18. #[derive(Clone)]
  19. struct ServerState {
  20. child: Arc<Mutex<Option<CommandChild>>>,
  21. status: futures::future::Shared<tokio::sync::oneshot::Receiver<Result<String, String>>>,
  22. }
  23. impl ServerState {
  24. pub fn new(
  25. child: Option<CommandChild>,
  26. status: tokio::sync::oneshot::Receiver<Result<String, String>>,
  27. ) -> Self {
  28. Self {
  29. child: Arc::new(Mutex::new(child)),
  30. status: status.shared(),
  31. }
  32. }
  33. pub fn set_child(&self, child: Option<CommandChild>) {
  34. *self.child.lock().unwrap() = child;
  35. }
  36. }
  37. #[derive(Clone)]
  38. struct LogState(Arc<Mutex<VecDeque<String>>>);
  39. const MAX_LOG_ENTRIES: usize = 200;
  40. #[tauri::command]
  41. fn kill_sidecar(app: AppHandle) {
  42. let Some(server_state) = app.try_state::<ServerState>() else {
  43. println!("Server not running");
  44. return;
  45. };
  46. let Some(server_state) = server_state
  47. .child
  48. .lock()
  49. .expect("Failed to acquire mutex lock")
  50. .take()
  51. else {
  52. println!("Server state missing");
  53. return;
  54. };
  55. let _ = server_state.kill();
  56. println!("Killed server");
  57. }
  58. async fn get_logs(app: AppHandle) -> Result<String, String> {
  59. let log_state = app.try_state::<LogState>().ok_or("Log state not found")?;
  60. let logs = log_state
  61. .0
  62. .lock()
  63. .map_err(|_| "Failed to acquire log lock")?;
  64. Ok(logs.iter().cloned().collect::<Vec<_>>().join(""))
  65. }
  66. #[tauri::command]
  67. async fn ensure_server_ready(state: State<'_, ServerState>) -> Result<String, String> {
  68. state
  69. .status
  70. .clone()
  71. .await
  72. .map_err(|_| "Failed to get server status".to_string())?
  73. }
  74. #[tauri::command]
  75. fn get_default_server_url(app: AppHandle) -> Result<Option<String>, String> {
  76. let store = app
  77. .store(SETTINGS_STORE)
  78. .map_err(|e| format!("Failed to open settings store: {}", e))?;
  79. let value = store.get(DEFAULT_SERVER_URL_KEY);
  80. match value {
  81. Some(v) => Ok(v.as_str().map(String::from)),
  82. None => Ok(None),
  83. }
  84. }
  85. #[tauri::command]
  86. async fn set_default_server_url(app: AppHandle, url: Option<String>) -> Result<(), String> {
  87. let store = app
  88. .store(SETTINGS_STORE)
  89. .map_err(|e| format!("Failed to open settings store: {}", e))?;
  90. match url {
  91. Some(u) => {
  92. store.set(DEFAULT_SERVER_URL_KEY, serde_json::Value::String(u));
  93. }
  94. None => {
  95. store.delete(DEFAULT_SERVER_URL_KEY);
  96. }
  97. }
  98. store
  99. .save()
  100. .map_err(|e| format!("Failed to save settings: {}", e))?;
  101. Ok(())
  102. }
  103. fn get_sidecar_port() -> u32 {
  104. option_env!("OPENCODE_PORT")
  105. .map(|s| s.to_string())
  106. .or_else(|| std::env::var("OPENCODE_PORT").ok())
  107. .and_then(|port_str| port_str.parse().ok())
  108. .unwrap_or_else(|| {
  109. TcpListener::bind("127.0.0.1:0")
  110. .expect("Failed to bind to find free port")
  111. .local_addr()
  112. .expect("Failed to get local address")
  113. .port()
  114. }) as u32
  115. }
  116. fn spawn_sidecar(app: &AppHandle, port: u32) -> CommandChild {
  117. let log_state = app.state::<LogState>();
  118. let log_state_clone = log_state.inner().clone();
  119. println!("spawning sidecar on port {port}");
  120. let (mut rx, child) = cli::create_command(app, format!("serve --port {port}").as_str())
  121. .spawn()
  122. .expect("Failed to spawn opencode");
  123. tauri::async_runtime::spawn(async move {
  124. while let Some(event) = rx.recv().await {
  125. match event {
  126. CommandEvent::Stdout(line_bytes) => {
  127. let line = String::from_utf8_lossy(&line_bytes);
  128. print!("{line}");
  129. // Store log in shared state
  130. if let Ok(mut logs) = log_state_clone.0.lock() {
  131. logs.push_back(format!("[STDOUT] {}", line));
  132. // Keep only the last MAX_LOG_ENTRIES
  133. while logs.len() > MAX_LOG_ENTRIES {
  134. logs.pop_front();
  135. }
  136. }
  137. }
  138. CommandEvent::Stderr(line_bytes) => {
  139. let line = String::from_utf8_lossy(&line_bytes);
  140. eprint!("{line}");
  141. // Store log in shared state
  142. if let Ok(mut logs) = log_state_clone.0.lock() {
  143. logs.push_back(format!("[STDERR] {}", line));
  144. // Keep only the last MAX_LOG_ENTRIES
  145. while logs.len() > MAX_LOG_ENTRIES {
  146. logs.pop_front();
  147. }
  148. }
  149. }
  150. _ => {}
  151. }
  152. }
  153. });
  154. child
  155. }
  156. async fn check_server_health(url: &str) -> bool {
  157. let health_url = format!("{}/health", url.trim_end_matches('/'));
  158. let client = reqwest::Client::builder()
  159. .timeout(Duration::from_secs(3))
  160. .build();
  161. let Ok(client) = client else {
  162. return false;
  163. };
  164. client
  165. .get(&health_url)
  166. .send()
  167. .await
  168. .map(|r| r.status().is_success())
  169. .unwrap_or(false)
  170. }
  171. #[cfg_attr(mobile, tauri::mobile_entry_point)]
  172. pub fn run() {
  173. let updater_enabled = option_env!("TAURI_SIGNING_PRIVATE_KEY").is_some();
  174. let mut builder = tauri::Builder::default()
  175. .plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
  176. // Focus existing window when another instance is launched
  177. if let Some(window) = app.get_webview_window("main") {
  178. let _ = window.set_focus();
  179. let _ = window.unminimize();
  180. }
  181. }))
  182. .plugin(tauri_plugin_os::init())
  183. .plugin(tauri_plugin_window_state::Builder::new().build())
  184. .plugin(tauri_plugin_store::Builder::new().build())
  185. .plugin(tauri_plugin_dialog::init())
  186. .plugin(tauri_plugin_shell::init())
  187. .plugin(tauri_plugin_process::init())
  188. .plugin(tauri_plugin_opener::init())
  189. .plugin(tauri_plugin_clipboard_manager::init())
  190. .plugin(tauri_plugin_http::init())
  191. .plugin(tauri_plugin_notification::init())
  192. .plugin(PinchZoomDisablePlugin)
  193. .invoke_handler(tauri::generate_handler![
  194. kill_sidecar,
  195. install_cli,
  196. ensure_server_ready,
  197. get_default_server_url,
  198. set_default_server_url
  199. ])
  200. .setup(move |app| {
  201. let app = app.handle().clone();
  202. // Initialize log state
  203. app.manage(LogState(Arc::new(Mutex::new(VecDeque::new()))));
  204. let primary_monitor = app.primary_monitor().ok().flatten();
  205. let size = primary_monitor
  206. .map(|m| m.size().to_logical(m.scale_factor()))
  207. .unwrap_or(LogicalSize::new(1920, 1080));
  208. #[allow(unused_mut)]
  209. let mut window_builder =
  210. WebviewWindow::builder(&app, "main", WebviewUrl::App("/".into()))
  211. .title("OpenCode")
  212. .inner_size(size.width as f64, size.height as f64)
  213. .decorations(true)
  214. .zoom_hotkeys_enabled(true)
  215. .disable_drag_drop_handler()
  216. .initialization_script(format!(
  217. r#"
  218. window.__OPENCODE__ ??= {{}};
  219. window.__OPENCODE__.updaterEnabled = {updater_enabled};
  220. "#
  221. ));
  222. #[cfg(target_os = "macos")]
  223. {
  224. window_builder = window_builder
  225. .title_bar_style(tauri::TitleBarStyle::Overlay)
  226. .hidden_title(true);
  227. }
  228. window_builder.build().expect("Failed to create window");
  229. let (tx, rx) = tokio::sync::oneshot::channel();
  230. app.manage(ServerState::new(None, rx));
  231. {
  232. let app = app.clone();
  233. tauri::async_runtime::spawn(async move {
  234. let mut custom_url = None;
  235. if let Some(url) = get_default_server_url(app.clone()).ok().flatten() {
  236. println!("Using desktop-specific custom URL: {url}");
  237. custom_url = Some(url);
  238. }
  239. if custom_url.is_none()
  240. && let Some(cli_config) = cli::get_config(&app).await
  241. && let Some(url) = get_server_url_from_config(&cli_config)
  242. {
  243. println!("Using custom server URL from config: {url}");
  244. custom_url = Some(url);
  245. }
  246. let res = match setup_server_connection(&app, custom_url).await {
  247. Ok((child, url)) => {
  248. app.state::<ServerState>().set_child(child);
  249. Ok(url)
  250. }
  251. Err(e) => Err(e),
  252. };
  253. let _ = tx.send(res);
  254. });
  255. }
  256. {
  257. let app = app.clone();
  258. tauri::async_runtime::spawn(async move {
  259. if let Err(e) = sync_cli(app) {
  260. eprintln!("Failed to sync CLI: {e}");
  261. }
  262. });
  263. }
  264. Ok(())
  265. });
  266. if updater_enabled {
  267. builder = builder.plugin(tauri_plugin_updater::Builder::new().build());
  268. }
  269. builder
  270. .build(tauri::generate_context!())
  271. .expect("error while running tauri application")
  272. .run(|app, event| {
  273. if let RunEvent::Exit = event {
  274. println!("Received Exit");
  275. kill_sidecar(app.clone());
  276. }
  277. });
  278. }
  279. fn get_server_url_from_config(config: &cli::Config) -> Option<String> {
  280. let server = config.server.as_ref()?;
  281. let port = server.port?;
  282. println!("server.port found in OC config: {port}");
  283. let hostname = server.hostname.as_ref();
  284. Some(format!(
  285. "http://{}:{}",
  286. hostname.map(|v| v.as_str()).unwrap_or("127.0.0.1"),
  287. port
  288. ))
  289. }
  290. async fn setup_server_connection(
  291. app: &AppHandle,
  292. custom_url: Option<String>,
  293. ) -> Result<(Option<CommandChild>, String), String> {
  294. if let Some(url) = custom_url {
  295. loop {
  296. if check_server_health(&url).await {
  297. println!("Connected to custom server: {}", url);
  298. return Ok((None, url.clone()));
  299. }
  300. const RETRY: &str = "Retry";
  301. let res = app.dialog()
  302. .message(format!("Could not connect to configured server:\n{}\n\nWould you like to retry or start a local server instead?", url))
  303. .title("Connection Failed")
  304. .buttons(MessageDialogButtons::OkCancelCustom(RETRY.to_string(), "Start Local".to_string()))
  305. .blocking_show_with_result();
  306. match res {
  307. MessageDialogResult::Custom(name) if name == RETRY => {
  308. continue;
  309. }
  310. _ => {
  311. break;
  312. }
  313. }
  314. }
  315. }
  316. let local_port = get_sidecar_port();
  317. let local_url = format!("http://127.0.0.1:{local_port}");
  318. if !check_server_health(&local_url).await {
  319. match spawn_local_server(app, local_port).await {
  320. Ok(child) => Ok(Some(child)),
  321. Err(err) => Err(err),
  322. }
  323. } else {
  324. Ok(None)
  325. }
  326. .map(|child| (child, local_url))
  327. }
  328. async fn spawn_local_server(app: &AppHandle, port: u32) -> Result<CommandChild, String> {
  329. let child = spawn_sidecar(app, port);
  330. let url = format!("http://127.0.0.1:{port}");
  331. let timestamp = Instant::now();
  332. loop {
  333. if timestamp.elapsed() > Duration::from_secs(7) {
  334. break Err(format!(
  335. "Failed to spawn OpenCode Server. Logs:\n{}",
  336. get_logs(app.clone()).await.unwrap()
  337. ));
  338. }
  339. tokio::time::sleep(Duration::from_millis(10)).await;
  340. if check_server_health(&url).await {
  341. println!("Server ready after {:?}", timestamp.elapsed());
  342. break Ok(child);
  343. }
  344. }
  345. }