lib.rs 18 KB

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