lib.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. mod cli;
  2. mod window_customizer;
  3. use cli::{get_sidecar_path, install_cli, sync_cli};
  4. use std::{
  5. collections::VecDeque,
  6. net::{SocketAddr, TcpListener},
  7. sync::{Arc, Mutex},
  8. time::{Duration, Instant},
  9. };
  10. use tauri::{
  11. path::BaseDirectory, AppHandle, LogicalSize, Manager, RunEvent, WebviewUrl, WebviewWindow,
  12. };
  13. use tauri_plugin_clipboard_manager::ClipboardExt;
  14. use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogResult};
  15. use tauri_plugin_shell::process::{CommandChild, CommandEvent};
  16. use tauri_plugin_shell::ShellExt;
  17. use tokio::net::TcpSocket;
  18. use crate::window_customizer::PinchZoomDisablePlugin;
  19. #[derive(Clone)]
  20. struct ServerState(Arc<Mutex<Option<CommandChild>>>);
  21. #[derive(Clone)]
  22. struct LogState(Arc<Mutex<VecDeque<String>>>);
  23. const MAX_LOG_ENTRIES: usize = 200;
  24. #[tauri::command]
  25. fn kill_sidecar(app: AppHandle) {
  26. let Some(server_state) = app.try_state::<ServerState>() else {
  27. println!("Server not running");
  28. return;
  29. };
  30. let Some(server_state) = server_state
  31. .0
  32. .lock()
  33. .expect("Failed to acquire mutex lock")
  34. .take()
  35. else {
  36. println!("Server state missing");
  37. return;
  38. };
  39. let _ = server_state.kill();
  40. println!("Killed server");
  41. }
  42. #[tauri::command]
  43. async fn copy_logs_to_clipboard(app: AppHandle) -> Result<(), String> {
  44. let log_state = app.try_state::<LogState>().ok_or("Log state not found")?;
  45. let logs = log_state
  46. .0
  47. .lock()
  48. .map_err(|_| "Failed to acquire log lock")?;
  49. let log_text = logs.iter().cloned().collect::<Vec<_>>().join("");
  50. app.clipboard()
  51. .write_text(log_text)
  52. .map_err(|e| format!("Failed to copy to clipboard: {}", e))?;
  53. Ok(())
  54. }
  55. #[tauri::command]
  56. async fn get_logs(app: AppHandle) -> Result<String, String> {
  57. let log_state = app.try_state::<LogState>().ok_or("Log state not found")?;
  58. let logs = log_state
  59. .0
  60. .lock()
  61. .map_err(|_| "Failed to acquire log lock")?;
  62. Ok(logs.iter().cloned().collect::<Vec<_>>().join(""))
  63. }
  64. fn get_sidecar_port() -> u32 {
  65. option_env!("OPENCODE_PORT")
  66. .map(|s| s.to_string())
  67. .or_else(|| std::env::var("OPENCODE_PORT").ok())
  68. .and_then(|port_str| port_str.parse().ok())
  69. .unwrap_or_else(|| {
  70. TcpListener::bind("127.0.0.1:0")
  71. .expect("Failed to bind to find free port")
  72. .local_addr()
  73. .expect("Failed to get local address")
  74. .port()
  75. }) as u32
  76. }
  77. fn get_user_shell() -> String {
  78. std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string())
  79. }
  80. fn spawn_sidecar(app: &AppHandle, port: u32) -> CommandChild {
  81. let log_state = app.state::<LogState>();
  82. let log_state_clone = log_state.inner().clone();
  83. let state_dir = app
  84. .path()
  85. .resolve("", BaseDirectory::AppLocalData)
  86. .expect("Failed to resolve app local data dir");
  87. #[cfg(target_os = "windows")]
  88. let (mut rx, child) = app
  89. .shell()
  90. .sidecar("opencode-cli")
  91. .unwrap()
  92. .env("OPENCODE_EXPERIMENTAL_ICON_DISCOVERY", "true")
  93. .env("OPENCODE_CLIENT", "desktop")
  94. .env("XDG_STATE_HOME", &state_dir)
  95. .args(["serve", &format!("--port={port}")])
  96. .spawn()
  97. .expect("Failed to spawn opencode");
  98. #[cfg(not(target_os = "windows"))]
  99. let (mut rx, child) = {
  100. let sidecar = get_sidecar_path();
  101. let shell = get_user_shell();
  102. app.shell()
  103. .command(&shell)
  104. .env("OPENCODE_EXPERIMENTAL_ICON_DISCOVERY", "true")
  105. .env("OPENCODE_CLIENT", "desktop")
  106. .env("XDG_STATE_HOME", &state_dir)
  107. .args([
  108. "-il",
  109. "-c",
  110. &format!("{} serve --port={}", sidecar.display(), port),
  111. ])
  112. .spawn()
  113. .expect("Failed to spawn opencode")
  114. };
  115. tauri::async_runtime::spawn(async move {
  116. while let Some(event) = rx.recv().await {
  117. match event {
  118. CommandEvent::Stdout(line_bytes) => {
  119. let line = String::from_utf8_lossy(&line_bytes);
  120. print!("{line}");
  121. // Store log in shared state
  122. if let Ok(mut logs) = log_state_clone.0.lock() {
  123. logs.push_back(format!("[STDOUT] {}", line));
  124. // Keep only the last MAX_LOG_ENTRIES
  125. while logs.len() > MAX_LOG_ENTRIES {
  126. logs.pop_front();
  127. }
  128. }
  129. }
  130. CommandEvent::Stderr(line_bytes) => {
  131. let line = String::from_utf8_lossy(&line_bytes);
  132. eprint!("{line}");
  133. // Store log in shared state
  134. if let Ok(mut logs) = log_state_clone.0.lock() {
  135. logs.push_back(format!("[STDERR] {}", line));
  136. // Keep only the last MAX_LOG_ENTRIES
  137. while logs.len() > MAX_LOG_ENTRIES {
  138. logs.pop_front();
  139. }
  140. }
  141. }
  142. _ => {}
  143. }
  144. }
  145. });
  146. child
  147. }
  148. async fn is_server_running(port: u32) -> bool {
  149. TcpSocket::new_v4()
  150. .unwrap()
  151. .connect(SocketAddr::new(
  152. "127.0.0.1".parse().expect("Failed to parse IP"),
  153. port as u16,
  154. ))
  155. .await
  156. .is_ok()
  157. }
  158. #[cfg_attr(mobile, tauri::mobile_entry_point)]
  159. pub fn run() {
  160. let updater_enabled = option_env!("TAURI_SIGNING_PRIVATE_KEY").is_some();
  161. let mut builder = tauri::Builder::default()
  162. .plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
  163. // Focus existing window when another instance is launched
  164. if let Some(window) = app.get_webview_window("main") {
  165. let _ = window.set_focus();
  166. let _ = window.unminimize();
  167. }
  168. }))
  169. .plugin(tauri_plugin_os::init())
  170. .plugin(tauri_plugin_window_state::Builder::new().build())
  171. .plugin(tauri_plugin_store::Builder::new().build())
  172. .plugin(tauri_plugin_dialog::init())
  173. .plugin(tauri_plugin_shell::init())
  174. .plugin(tauri_plugin_process::init())
  175. .plugin(tauri_plugin_opener::init())
  176. .plugin(tauri_plugin_clipboard_manager::init())
  177. .plugin(tauri_plugin_http::init())
  178. .plugin(tauri_plugin_notification::init())
  179. .plugin(PinchZoomDisablePlugin)
  180. .invoke_handler(tauri::generate_handler![
  181. kill_sidecar,
  182. copy_logs_to_clipboard,
  183. get_logs,
  184. install_cli
  185. ])
  186. .setup(move |app| {
  187. let app = app.handle().clone();
  188. // Initialize log state
  189. app.manage(LogState(Arc::new(Mutex::new(VecDeque::new()))));
  190. {
  191. let app = app.clone();
  192. tauri::async_runtime::spawn(async move {
  193. let port = get_sidecar_port();
  194. let should_spawn_sidecar = !is_server_running(port).await;
  195. let child = if should_spawn_sidecar {
  196. let child = spawn_sidecar(&app, port);
  197. let timestamp = Instant::now();
  198. loop {
  199. if timestamp.elapsed() > Duration::from_secs(7) {
  200. let res = app.dialog()
  201. .message("Failed to spawn OpenCode Server. Copy logs using the button below and send them to the team for assistance.")
  202. .title("Startup Failed")
  203. .buttons(MessageDialogButtons::OkCancelCustom("Copy Logs And Exit".to_string(), "Exit".to_string()))
  204. .blocking_show_with_result();
  205. if matches!(&res, MessageDialogResult::Custom(name) if name == "Copy Logs And Exit") {
  206. match copy_logs_to_clipboard(app.clone()).await {
  207. Ok(()) => println!("Logs copied to clipboard successfully"),
  208. Err(e) => println!("Failed to copy logs to clipboard: {}", e),
  209. }
  210. }
  211. app.exit(1);
  212. return;
  213. }
  214. tokio::time::sleep(Duration::from_millis(10)).await;
  215. if is_server_running(port).await {
  216. // give the server a little bit more time to warm up
  217. tokio::time::sleep(Duration::from_millis(10)).await;
  218. break;
  219. }
  220. }
  221. println!("Server ready after {:?}", timestamp.elapsed());
  222. Some(child)
  223. } else {
  224. None
  225. };
  226. let primary_monitor = app.primary_monitor().ok().flatten();
  227. let size = primary_monitor
  228. .map(|m| m.size().to_logical(m.scale_factor()))
  229. .unwrap_or(LogicalSize::new(1920, 1080));
  230. let mut window_builder =
  231. WebviewWindow::builder(&app, "main", WebviewUrl::App("/".into()))
  232. .title("OpenCode")
  233. .inner_size(size.width as f64, size.height as f64)
  234. .decorations(true)
  235. .zoom_hotkeys_enabled(true)
  236. .disable_drag_drop_handler()
  237. .initialization_script(format!(
  238. r#"
  239. window.__OPENCODE__ ??= {{}};
  240. window.__OPENCODE__.updaterEnabled = {updater_enabled};
  241. window.__OPENCODE__.port = {port};
  242. "#
  243. ));
  244. #[cfg(target_os = "macos")]
  245. {
  246. window_builder = window_builder
  247. .title_bar_style(tauri::TitleBarStyle::Overlay)
  248. .hidden_title(true);
  249. }
  250. window_builder.build().expect("Failed to create window");
  251. app.manage(ServerState(Arc::new(Mutex::new(child))));
  252. });
  253. }
  254. {
  255. let app = app.clone();
  256. tauri::async_runtime::spawn(async move {
  257. if let Err(e) = sync_cli(app) {
  258. eprintln!("Failed to sync CLI: {e}");
  259. }
  260. });
  261. }
  262. Ok(())
  263. });
  264. if updater_enabled {
  265. builder = builder.plugin(tauri_plugin_updater::Builder::new().build());
  266. }
  267. builder
  268. .build(tauri::generate_context!())
  269. .expect("error while running tauri application")
  270. .run(|app, event| {
  271. if let RunEvent::Exit = event {
  272. println!("Received Exit");
  273. kill_sidecar(app.clone());
  274. }
  275. });
  276. }