lib.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. mod cli;
  2. #[cfg(windows)]
  3. mod job_object;
  4. mod markdown;
  5. mod window_customizer;
  6. use cli::{install_cli, sync_cli};
  7. use futures::FutureExt;
  8. use futures::future;
  9. #[cfg(windows)]
  10. use job_object::*;
  11. use std::{
  12. collections::VecDeque,
  13. net::TcpListener,
  14. sync::{Arc, Mutex},
  15. time::{Duration, Instant},
  16. };
  17. use tauri::{AppHandle, LogicalSize, Manager, RunEvent, State, WebviewWindowBuilder};
  18. #[cfg(any(target_os = "linux", all(debug_assertions, windows)))]
  19. use tauri_plugin_deep_link::DeepLinkExt;
  20. #[cfg(windows)]
  21. use tauri_plugin_decorum::WebviewWindowExt;
  22. use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogResult};
  23. use tauri_plugin_shell::process::{CommandChild, CommandEvent};
  24. use tauri_plugin_store::StoreExt;
  25. use tokio::sync::oneshot;
  26. use crate::window_customizer::PinchZoomDisablePlugin;
  27. const SETTINGS_STORE: &str = "opencode.settings.dat";
  28. const DEFAULT_SERVER_URL_KEY: &str = "defaultServerUrl";
  29. #[derive(Clone, serde::Serialize)]
  30. struct ServerReadyData {
  31. url: String,
  32. password: Option<String>,
  33. }
  34. #[derive(Clone)]
  35. struct ServerState {
  36. child: Arc<Mutex<Option<CommandChild>>>,
  37. status: future::Shared<oneshot::Receiver<Result<ServerReadyData, String>>>,
  38. }
  39. impl ServerState {
  40. pub fn new(
  41. child: Option<CommandChild>,
  42. status: oneshot::Receiver<Result<ServerReadyData, String>>,
  43. ) -> Self {
  44. Self {
  45. child: Arc::new(Mutex::new(child)),
  46. status: status.shared(),
  47. }
  48. }
  49. pub fn set_child(&self, child: Option<CommandChild>) {
  50. *self.child.lock().unwrap() = child;
  51. }
  52. }
  53. #[derive(Clone)]
  54. struct LogState(Arc<Mutex<VecDeque<String>>>);
  55. const MAX_LOG_ENTRIES: usize = 200;
  56. #[tauri::command]
  57. fn kill_sidecar(app: AppHandle) {
  58. let Some(server_state) = app.try_state::<ServerState>() else {
  59. println!("Server not running");
  60. return;
  61. };
  62. let Some(server_state) = server_state
  63. .child
  64. .lock()
  65. .expect("Failed to acquire mutex lock")
  66. .take()
  67. else {
  68. println!("Server state missing");
  69. return;
  70. };
  71. let _ = server_state.kill();
  72. println!("Killed server");
  73. }
  74. async fn get_logs(app: AppHandle) -> Result<String, String> {
  75. let log_state = app.try_state::<LogState>().ok_or("Log state not found")?;
  76. let logs = log_state
  77. .0
  78. .lock()
  79. .map_err(|_| "Failed to acquire log lock")?;
  80. Ok(logs.iter().cloned().collect::<Vec<_>>().join(""))
  81. }
  82. #[tauri::command]
  83. async fn ensure_server_ready(state: State<'_, ServerState>) -> Result<ServerReadyData, String> {
  84. state
  85. .status
  86. .clone()
  87. .await
  88. .map_err(|_| "Failed to get server status".to_string())?
  89. }
  90. #[tauri::command]
  91. fn get_default_server_url(app: AppHandle) -> Result<Option<String>, String> {
  92. let store = app
  93. .store(SETTINGS_STORE)
  94. .map_err(|e| format!("Failed to open settings store: {}", e))?;
  95. let value = store.get(DEFAULT_SERVER_URL_KEY);
  96. match value {
  97. Some(v) => Ok(v.as_str().map(String::from)),
  98. None => Ok(None),
  99. }
  100. }
  101. #[tauri::command]
  102. async fn set_default_server_url(app: AppHandle, url: Option<String>) -> Result<(), String> {
  103. let store = app
  104. .store(SETTINGS_STORE)
  105. .map_err(|e| format!("Failed to open settings store: {}", e))?;
  106. match url {
  107. Some(u) => {
  108. store.set(DEFAULT_SERVER_URL_KEY, serde_json::Value::String(u));
  109. }
  110. None => {
  111. store.delete(DEFAULT_SERVER_URL_KEY);
  112. }
  113. }
  114. store
  115. .save()
  116. .map_err(|e| format!("Failed to save settings: {}", e))?;
  117. Ok(())
  118. }
  119. fn get_sidecar_port() -> u32 {
  120. option_env!("OPENCODE_PORT")
  121. .map(|s| s.to_string())
  122. .or_else(|| std::env::var("OPENCODE_PORT").ok())
  123. .and_then(|port_str| port_str.parse().ok())
  124. .unwrap_or_else(|| {
  125. TcpListener::bind("127.0.0.1:0")
  126. .expect("Failed to bind to find free port")
  127. .local_addr()
  128. .expect("Failed to get local address")
  129. .port()
  130. }) as u32
  131. }
  132. fn spawn_sidecar(app: &AppHandle, hostname: &str, port: u32, password: &str) -> CommandChild {
  133. let log_state = app.state::<LogState>();
  134. let log_state_clone = log_state.inner().clone();
  135. println!("spawning sidecar on port {port}");
  136. let (mut rx, child) = cli::create_command(
  137. app,
  138. format!("serve --hostname {hostname} --port {port}").as_str(),
  139. )
  140. .env("OPENCODE_SERVER_USERNAME", "opencode")
  141. .env("OPENCODE_SERVER_PASSWORD", password)
  142. .spawn()
  143. .expect("Failed to spawn opencode");
  144. tauri::async_runtime::spawn(async move {
  145. while let Some(event) = rx.recv().await {
  146. match event {
  147. CommandEvent::Stdout(line_bytes) => {
  148. let line = String::from_utf8_lossy(&line_bytes);
  149. print!("{line}");
  150. // Store log in shared state
  151. if let Ok(mut logs) = log_state_clone.0.lock() {
  152. logs.push_back(format!("[STDOUT] {}", line));
  153. // Keep only the last MAX_LOG_ENTRIES
  154. while logs.len() > MAX_LOG_ENTRIES {
  155. logs.pop_front();
  156. }
  157. }
  158. }
  159. CommandEvent::Stderr(line_bytes) => {
  160. let line = String::from_utf8_lossy(&line_bytes);
  161. eprint!("{line}");
  162. // Store log in shared state
  163. if let Ok(mut logs) = log_state_clone.0.lock() {
  164. logs.push_back(format!("[STDERR] {}", line));
  165. // Keep only the last MAX_LOG_ENTRIES
  166. while logs.len() > MAX_LOG_ENTRIES {
  167. logs.pop_front();
  168. }
  169. }
  170. }
  171. _ => {}
  172. }
  173. }
  174. });
  175. child
  176. }
  177. fn url_is_localhost(url: &reqwest::Url) -> bool {
  178. url.host_str().is_some_and(|host| {
  179. host.eq_ignore_ascii_case("localhost")
  180. || host
  181. .parse::<std::net::IpAddr>()
  182. .is_ok_and(|ip| ip.is_loopback())
  183. })
  184. }
  185. async fn check_server_health(url: &str, password: Option<&str>) -> bool {
  186. let Ok(url) = reqwest::Url::parse(url) else {
  187. return false;
  188. };
  189. let mut builder = reqwest::Client::builder().timeout(Duration::from_secs(3));
  190. if url_is_localhost(&url) {
  191. // Some environments set proxy variables (HTTP_PROXY/HTTPS_PROXY/ALL_PROXY) without
  192. // excluding loopback. reqwest respects these by default, which can prevent the desktop
  193. // app from reaching its own local sidecar server.
  194. builder = builder.no_proxy();
  195. };
  196. let Ok(client) = builder.build() else {
  197. return false;
  198. };
  199. let Ok(health_url) = url.join("/global/health") else {
  200. return false;
  201. };
  202. let mut req = client.get(health_url);
  203. if let Some(password) = password {
  204. req = req.basic_auth("opencode", Some(password));
  205. }
  206. req.send()
  207. .await
  208. .map(|r| r.status().is_success())
  209. .unwrap_or(false)
  210. }
  211. #[cfg_attr(mobile, tauri::mobile_entry_point)]
  212. pub fn run() {
  213. let updater_enabled = option_env!("TAURI_SIGNING_PRIVATE_KEY").is_some();
  214. #[cfg(all(target_os = "macos", not(debug_assertions)))]
  215. let _ = std::process::Command::new("killall")
  216. .arg("opencode-cli")
  217. .output();
  218. let mut builder = tauri::Builder::default()
  219. .plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
  220. // Focus existing window when another instance is launched
  221. if let Some(window) = app.get_webview_window("main") {
  222. let _ = window.set_focus();
  223. let _ = window.unminimize();
  224. }
  225. }))
  226. .plugin(tauri_plugin_deep_link::init())
  227. .plugin(tauri_plugin_os::init())
  228. .plugin(
  229. tauri_plugin_window_state::Builder::new()
  230. .with_state_flags(
  231. tauri_plugin_window_state::StateFlags::all()
  232. - tauri_plugin_window_state::StateFlags::DECORATIONS,
  233. )
  234. .build(),
  235. )
  236. .plugin(tauri_plugin_store::Builder::new().build())
  237. .plugin(tauri_plugin_dialog::init())
  238. .plugin(tauri_plugin_shell::init())
  239. .plugin(tauri_plugin_process::init())
  240. .plugin(tauri_plugin_opener::init())
  241. .plugin(tauri_plugin_clipboard_manager::init())
  242. .plugin(tauri_plugin_http::init())
  243. .plugin(tauri_plugin_notification::init())
  244. .plugin(PinchZoomDisablePlugin)
  245. .plugin(tauri_plugin_decorum::init())
  246. .invoke_handler(tauri::generate_handler![
  247. kill_sidecar,
  248. install_cli,
  249. ensure_server_ready,
  250. get_default_server_url,
  251. set_default_server_url,
  252. markdown::parse_markdown_command
  253. ])
  254. .setup(move |app| {
  255. #[cfg(any(target_os = "linux", all(debug_assertions, windows)))]
  256. app.deep_link().register_all().ok();
  257. let app = app.handle().clone();
  258. // Initialize log state
  259. app.manage(LogState(Arc::new(Mutex::new(VecDeque::new()))));
  260. #[cfg(windows)]
  261. app.manage(JobObjectState::new());
  262. let primary_monitor = app.primary_monitor().ok().flatten();
  263. let size = primary_monitor
  264. .map(|m| m.size().to_logical(m.scale_factor()))
  265. .unwrap_or(LogicalSize::new(1920, 1080));
  266. let config = app
  267. .config()
  268. .app
  269. .windows
  270. .iter()
  271. .find(|w| w.label == "main")
  272. .expect("main window config missing");
  273. let window_builder = WebviewWindowBuilder::from_config(&app, config)
  274. .expect("Failed to create window builder from config")
  275. .inner_size(size.width as f64, size.height as f64)
  276. .initialization_script(format!(
  277. r#"
  278. window.__OPENCODE__ ??= {{}};
  279. window.__OPENCODE__.updaterEnabled = {updater_enabled};
  280. "#
  281. ));
  282. #[cfg(target_os = "macos")]
  283. let window_builder = window_builder
  284. .title_bar_style(tauri::TitleBarStyle::Overlay)
  285. .hidden_title(true);
  286. #[cfg(windows)]
  287. let window_builder = window_builder
  288. // Some VPNs set a global/system proxy that WebView2 applies even for loopback
  289. // connections, which breaks the app's localhost sidecar server.
  290. // Note: when setting additional args, we must re-apply wry's default
  291. // `--disable-features=...` flags.
  292. .additional_browser_args(
  293. "--proxy-bypass-list=<-loopback> --disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection",
  294. )
  295. .decorations(false);
  296. let window = window_builder.build().expect("Failed to create window");
  297. #[cfg(windows)]
  298. let _ = window.create_overlay_titlebar();
  299. let (tx, rx) = oneshot::channel();
  300. app.manage(ServerState::new(None, rx));
  301. {
  302. let app = app.clone();
  303. tauri::async_runtime::spawn(async move {
  304. let mut custom_url = None;
  305. if let Some(url) = get_default_server_url(app.clone()).ok().flatten() {
  306. println!("Using desktop-specific custom URL: {url}");
  307. custom_url = Some(url);
  308. }
  309. if custom_url.is_none()
  310. && let Some(cli_config) = cli::get_config(&app).await
  311. && let Some(url) = get_server_url_from_config(&cli_config)
  312. {
  313. println!("Using custom server URL from config: {url}");
  314. custom_url = Some(url);
  315. }
  316. let res = match setup_server_connection(&app, custom_url).await {
  317. Ok((child, url)) => {
  318. #[cfg(windows)]
  319. if let Some(child) = &child {
  320. let job_state = app.state::<JobObjectState>();
  321. job_state.assign_pid(child.pid());
  322. }
  323. app.state::<ServerState>().set_child(child);
  324. Ok(url)
  325. }
  326. Err(e) => Err(e),
  327. };
  328. let _ = tx.send(res);
  329. });
  330. }
  331. {
  332. let app = app.clone();
  333. tauri::async_runtime::spawn(async move {
  334. if let Err(e) = sync_cli(app) {
  335. eprintln!("Failed to sync CLI: {e}");
  336. }
  337. });
  338. }
  339. Ok(())
  340. });
  341. if updater_enabled {
  342. builder = builder.plugin(tauri_plugin_updater::Builder::new().build());
  343. }
  344. builder
  345. .build(tauri::generate_context!())
  346. .expect("error while running tauri application")
  347. .run(|app, event| {
  348. if let RunEvent::Exit = event {
  349. println!("Received Exit");
  350. kill_sidecar(app.clone());
  351. }
  352. });
  353. }
  354. /// Converts a bind address hostname to a valid URL hostname for connection.
  355. /// - `0.0.0.0` and `::` are wildcard bind addresses, not valid connect targets
  356. /// - IPv6 addresses need brackets in URLs (e.g., `::1` -> `[::1]`)
  357. fn normalize_hostname_for_url(hostname: &str) -> String {
  358. // Wildcard bind addresses -> localhost equivalents
  359. if hostname == "0.0.0.0" {
  360. return "127.0.0.1".to_string();
  361. }
  362. if hostname == "::" {
  363. return "[::1]".to_string();
  364. }
  365. // IPv6 addresses need brackets in URLs
  366. if hostname.contains(':') && !hostname.starts_with('[') {
  367. return format!("[{}]", hostname);
  368. }
  369. hostname.to_string()
  370. }
  371. fn get_server_url_from_config(config: &cli::Config) -> Option<String> {
  372. let server = config.server.as_ref()?;
  373. let port = server.port?;
  374. println!("server.port found in OC config: {port}");
  375. let hostname = server
  376. .hostname
  377. .as_ref()
  378. .map(|v| normalize_hostname_for_url(v))
  379. .unwrap_or_else(|| "127.0.0.1".to_string());
  380. Some(format!("http://{}:{}", hostname, port))
  381. }
  382. async fn setup_server_connection(
  383. app: &AppHandle,
  384. custom_url: Option<String>,
  385. ) -> Result<(Option<CommandChild>, ServerReadyData), String> {
  386. if let Some(url) = custom_url {
  387. loop {
  388. if check_server_health(&url, None).await {
  389. println!("Connected to custom server: {}", url);
  390. return Ok((
  391. None,
  392. ServerReadyData {
  393. url: url.clone(),
  394. password: None,
  395. },
  396. ));
  397. }
  398. const RETRY: &str = "Retry";
  399. let res = app.dialog()
  400. .message(format!("Could not connect to configured server:\n{}\n\nWould you like to retry or start a local server instead?", url))
  401. .title("Connection Failed")
  402. .buttons(MessageDialogButtons::OkCancelCustom(RETRY.to_string(), "Start Local".to_string()))
  403. .blocking_show_with_result();
  404. match res {
  405. MessageDialogResult::Custom(name) if name == RETRY => {
  406. continue;
  407. }
  408. _ => {
  409. break;
  410. }
  411. }
  412. }
  413. }
  414. let local_port = get_sidecar_port();
  415. let hostname = "127.0.0.1";
  416. let local_url = format!("http://{hostname}:{local_port}");
  417. if !check_server_health(&local_url, None).await {
  418. let password = uuid::Uuid::new_v4().to_string();
  419. match spawn_local_server(app, hostname, local_port, &password).await {
  420. Ok(child) => Ok((
  421. Some(child),
  422. ServerReadyData {
  423. url: local_url,
  424. password: Some(password),
  425. },
  426. )),
  427. Err(err) => Err(err),
  428. }
  429. } else {
  430. Ok((
  431. None,
  432. ServerReadyData {
  433. url: local_url,
  434. password: None,
  435. },
  436. ))
  437. }
  438. }
  439. async fn spawn_local_server(
  440. app: &AppHandle,
  441. hostname: &str,
  442. port: u32,
  443. password: &str,
  444. ) -> Result<CommandChild, String> {
  445. let child = spawn_sidecar(app, hostname, port, password);
  446. let url = format!("http://{hostname}:{port}");
  447. let timestamp = Instant::now();
  448. loop {
  449. if timestamp.elapsed() > Duration::from_secs(30) {
  450. break Err(format!(
  451. "Failed to spawn OpenCode Server. Logs:\n{}",
  452. get_logs(app.clone()).await.unwrap()
  453. ));
  454. }
  455. tokio::time::sleep(Duration::from_millis(10)).await;
  456. if check_server_health(&url, Some(password)).await {
  457. println!("Server ready after {:?}", timestamp.elapsed());
  458. break Ok(child);
  459. }
  460. }
  461. }