lib.rs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. mod cli;
  2. mod constants;
  3. #[cfg(target_os = "linux")]
  4. pub mod linux_display;
  5. #[cfg(target_os = "linux")]
  6. pub mod linux_windowing;
  7. mod logging;
  8. mod markdown;
  9. mod os;
  10. mod server;
  11. mod window_customizer;
  12. mod windows;
  13. use crate::cli::CommandChild;
  14. use futures::{
  15. FutureExt, TryFutureExt,
  16. future::{self, Shared},
  17. };
  18. use std::{
  19. env,
  20. net::TcpListener,
  21. path::PathBuf,
  22. process::Command,
  23. sync::{Arc, Mutex},
  24. time::Duration,
  25. };
  26. use tauri::{AppHandle, Listener, Manager, RunEvent, State, ipc::Channel};
  27. #[cfg(any(target_os = "linux", all(debug_assertions, windows)))]
  28. use tauri_plugin_deep_link::DeepLinkExt;
  29. use tauri_specta::Event;
  30. use tokio::{
  31. sync::{oneshot, watch},
  32. time::{sleep, timeout},
  33. };
  34. use crate::cli::{sqlite_migration::SqliteMigrationProgress, sync_cli};
  35. use crate::constants::*;
  36. use crate::server::get_saved_server_url;
  37. use crate::windows::{LoadingWindow, MainWindow};
  38. #[derive(Clone, serde::Serialize, specta::Type, Debug)]
  39. struct ServerReadyData {
  40. url: String,
  41. username: Option<String>,
  42. password: Option<String>,
  43. is_sidecar: bool,
  44. }
  45. #[derive(Clone, Copy, serde::Serialize, specta::Type, Debug)]
  46. #[serde(tag = "phase", rename_all = "snake_case")]
  47. enum InitStep {
  48. ServerWaiting,
  49. SqliteWaiting,
  50. Done,
  51. }
  52. #[derive(serde::Deserialize, specta::Type)]
  53. #[serde(rename_all = "snake_case")]
  54. enum WslPathMode {
  55. Windows,
  56. Linux,
  57. }
  58. struct InitState {
  59. current: watch::Receiver<InitStep>,
  60. }
  61. #[derive(Clone)]
  62. struct ServerState {
  63. child: Arc<Mutex<Option<CommandChild>>>,
  64. status: future::Shared<oneshot::Receiver<Result<ServerReadyData, String>>>,
  65. }
  66. impl ServerState {
  67. pub fn new(
  68. child: Option<CommandChild>,
  69. status: Shared<oneshot::Receiver<Result<ServerReadyData, String>>>,
  70. ) -> Self {
  71. Self {
  72. child: Arc::new(Mutex::new(child)),
  73. status,
  74. }
  75. }
  76. pub fn set_child(&self, child: Option<CommandChild>) {
  77. *self.child.lock().unwrap() = child;
  78. }
  79. }
  80. #[tauri::command]
  81. #[specta::specta]
  82. fn kill_sidecar(app: AppHandle) {
  83. let Some(server_state) = app.try_state::<ServerState>() else {
  84. tracing::info!("Server not running");
  85. return;
  86. };
  87. let Some(server_state) = server_state
  88. .child
  89. .lock()
  90. .expect("Failed to acquire mutex lock")
  91. .take()
  92. else {
  93. tracing::info!("Server state missing");
  94. return;
  95. };
  96. let _ = server_state.kill();
  97. tracing::info!("Killed server");
  98. }
  99. fn get_logs() -> String {
  100. logging::tail()
  101. }
  102. #[tauri::command]
  103. #[specta::specta]
  104. async fn await_initialization(
  105. state: State<'_, ServerState>,
  106. init_state: State<'_, InitState>,
  107. events: Channel<InitStep>,
  108. ) -> Result<ServerReadyData, String> {
  109. let mut rx = init_state.current.clone();
  110. let events = async {
  111. let e = *rx.borrow();
  112. let _ = events.send(e);
  113. while rx.changed().await.is_ok() {
  114. let step = *rx.borrow_and_update();
  115. let _ = events.send(step);
  116. if matches!(step, InitStep::Done) {
  117. break;
  118. }
  119. }
  120. };
  121. future::join(state.status.clone(), events)
  122. .await
  123. .0
  124. .map_err(|_| "Failed to get server status".to_string())?
  125. }
  126. #[tauri::command]
  127. #[specta::specta]
  128. fn check_app_exists(app_name: &str) -> bool {
  129. #[cfg(target_os = "windows")]
  130. {
  131. os::windows::check_windows_app(app_name)
  132. }
  133. #[cfg(target_os = "macos")]
  134. {
  135. check_macos_app(app_name)
  136. }
  137. #[cfg(target_os = "linux")]
  138. {
  139. check_linux_app(app_name)
  140. }
  141. }
  142. #[tauri::command]
  143. #[specta::specta]
  144. fn resolve_app_path(app_name: &str) -> Option<String> {
  145. #[cfg(target_os = "windows")]
  146. {
  147. os::windows::resolve_windows_app_path(app_name)
  148. }
  149. #[cfg(not(target_os = "windows"))]
  150. {
  151. // On macOS/Linux, just return the app_name as-is since
  152. // the opener plugin handles them correctly
  153. Some(app_name.to_string())
  154. }
  155. }
  156. #[cfg(target_os = "macos")]
  157. fn check_macos_app(app_name: &str) -> bool {
  158. // Check common installation locations
  159. let mut app_locations = vec![
  160. format!("/Applications/{}.app", app_name),
  161. format!("/System/Applications/{}.app", app_name),
  162. ];
  163. if let Ok(home) = std::env::var("HOME") {
  164. app_locations.push(format!("{}/Applications/{}.app", home, app_name));
  165. }
  166. for location in app_locations {
  167. if std::path::Path::new(&location).exists() {
  168. return true;
  169. }
  170. }
  171. // Also check if command exists in PATH
  172. Command::new("which")
  173. .arg(app_name)
  174. .output()
  175. .map(|output| output.status.success())
  176. .unwrap_or(false)
  177. }
  178. #[derive(serde::Serialize, serde::Deserialize, specta::Type)]
  179. #[serde(rename_all = "camelCase")]
  180. pub enum LinuxDisplayBackend {
  181. Wayland,
  182. Auto,
  183. }
  184. #[tauri::command]
  185. #[specta::specta]
  186. fn get_display_backend() -> Option<LinuxDisplayBackend> {
  187. #[cfg(target_os = "linux")]
  188. {
  189. let prefer = linux_display::read_wayland().unwrap_or(false);
  190. return Some(if prefer {
  191. LinuxDisplayBackend::Wayland
  192. } else {
  193. LinuxDisplayBackend::Auto
  194. });
  195. }
  196. #[cfg(not(target_os = "linux"))]
  197. None
  198. }
  199. #[tauri::command]
  200. #[specta::specta]
  201. fn set_display_backend(_app: AppHandle, _backend: LinuxDisplayBackend) -> Result<(), String> {
  202. #[cfg(target_os = "linux")]
  203. {
  204. let prefer = matches!(_backend, LinuxDisplayBackend::Wayland);
  205. return linux_display::write_wayland(&_app, prefer);
  206. }
  207. #[cfg(not(target_os = "linux"))]
  208. Ok(())
  209. }
  210. #[cfg(target_os = "linux")]
  211. fn check_linux_app(app_name: &str) -> bool {
  212. return true;
  213. }
  214. #[tauri::command]
  215. #[specta::specta]
  216. fn wsl_path(path: String, mode: Option<WslPathMode>) -> Result<String, String> {
  217. if !cfg!(windows) {
  218. return Ok(path);
  219. }
  220. let flag = match mode.unwrap_or(WslPathMode::Linux) {
  221. WslPathMode::Windows => "-w",
  222. WslPathMode::Linux => "-u",
  223. };
  224. let output = if path.starts_with('~') {
  225. let suffix = path.strip_prefix('~').unwrap_or("");
  226. let escaped = suffix.replace('"', "\\\"");
  227. let cmd = format!("wslpath {flag} \"$HOME{escaped}\"");
  228. Command::new("wsl")
  229. .args(["-e", "sh", "-lc", &cmd])
  230. .output()
  231. .map_err(|e| format!("Failed to run wslpath: {e}"))?
  232. } else {
  233. Command::new("wsl")
  234. .args(["-e", "wslpath", flag, &path])
  235. .output()
  236. .map_err(|e| format!("Failed to run wslpath: {e}"))?
  237. };
  238. if !output.status.success() {
  239. let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
  240. if stderr.is_empty() {
  241. return Err("wslpath failed".to_string());
  242. }
  243. return Err(stderr);
  244. }
  245. Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
  246. }
  247. #[cfg_attr(mobile, tauri::mobile_entry_point)]
  248. pub fn run() {
  249. let builder = make_specta_builder();
  250. #[cfg(debug_assertions)] // <- Only export on non-release builds
  251. export_types(&builder);
  252. #[cfg(all(target_os = "macos", not(debug_assertions)))]
  253. let _ = std::process::Command::new("killall")
  254. .arg("opencode-cli")
  255. .output();
  256. let mut builder = tauri::Builder::default()
  257. .plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
  258. // Focus existing window when another instance is launched
  259. if let Some(window) = app.get_webview_window(MainWindow::LABEL) {
  260. let _ = window.set_focus();
  261. let _ = window.unminimize();
  262. }
  263. }))
  264. .plugin(tauri_plugin_deep_link::init())
  265. .plugin(tauri_plugin_os::init())
  266. .plugin(
  267. tauri_plugin_window_state::Builder::new()
  268. .with_state_flags(window_state_flags())
  269. .with_denylist(&[LoadingWindow::LABEL])
  270. .build(),
  271. )
  272. .plugin(tauri_plugin_store::Builder::new().build())
  273. .plugin(tauri_plugin_dialog::init())
  274. .plugin(tauri_plugin_shell::init())
  275. .plugin(tauri_plugin_process::init())
  276. .plugin(tauri_plugin_opener::init())
  277. .plugin(tauri_plugin_clipboard_manager::init())
  278. .plugin(tauri_plugin_http::init())
  279. .plugin(tauri_plugin_notification::init())
  280. .plugin(crate::window_customizer::PinchZoomDisablePlugin)
  281. .plugin(tauri_plugin_decorum::init())
  282. .invoke_handler(builder.invoke_handler())
  283. .setup(move |app| {
  284. let handle = app.handle().clone();
  285. let log_dir = app
  286. .path()
  287. .app_log_dir()
  288. .expect("failed to resolve app log dir");
  289. // Hold the guard in managed state so it lives for the app's lifetime,
  290. // ensuring all buffered logs are flushed on shutdown.
  291. handle.manage(logging::init(&log_dir));
  292. builder.mount_events(&handle);
  293. tauri::async_runtime::spawn(initialize(handle));
  294. Ok(())
  295. });
  296. if UPDATER_ENABLED {
  297. builder = builder.plugin(tauri_plugin_updater::Builder::new().build());
  298. }
  299. builder
  300. .build(tauri::generate_context!())
  301. .expect("error while running tauri application")
  302. .run(|app, event| {
  303. if let RunEvent::Exit = event {
  304. tracing::info!("Received Exit");
  305. kill_sidecar(app.clone());
  306. }
  307. });
  308. }
  309. fn make_specta_builder() -> tauri_specta::Builder<tauri::Wry> {
  310. tauri_specta::Builder::<tauri::Wry>::new()
  311. // Then register them (separated by a comma)
  312. .commands(tauri_specta::collect_commands![
  313. kill_sidecar,
  314. cli::install_cli,
  315. await_initialization,
  316. server::get_default_server_url,
  317. server::set_default_server_url,
  318. server::get_wsl_config,
  319. server::set_wsl_config,
  320. get_display_backend,
  321. set_display_backend,
  322. markdown::parse_markdown_command,
  323. check_app_exists,
  324. wsl_path,
  325. resolve_app_path
  326. ])
  327. .events(tauri_specta::collect_events![
  328. LoadingWindowComplete,
  329. SqliteMigrationProgress
  330. ])
  331. .error_handling(tauri_specta::ErrorHandlingMode::Throw)
  332. }
  333. fn export_types(builder: &tauri_specta::Builder<tauri::Wry>) {
  334. builder
  335. .export(
  336. specta_typescript::Typescript::default(),
  337. "../src/bindings.ts",
  338. )
  339. .expect("Failed to export typescript bindings");
  340. }
  341. #[cfg(test)]
  342. #[test]
  343. fn test_export_types() {
  344. let builder = make_specta_builder();
  345. export_types(&builder);
  346. }
  347. #[derive(tauri_specta::Event, serde::Deserialize, specta::Type)]
  348. struct LoadingWindowComplete;
  349. async fn initialize(app: AppHandle) {
  350. tracing::info!("Initializing app");
  351. let (init_tx, init_rx) = watch::channel(InitStep::ServerWaiting);
  352. setup_app(&app, init_rx);
  353. spawn_cli_sync_task(app.clone());
  354. let (server_ready_tx, server_ready_rx) = oneshot::channel();
  355. let server_ready_rx = server_ready_rx.shared();
  356. app.manage(ServerState::new(None, server_ready_rx.clone()));
  357. let loading_window_complete = event_once_fut::<LoadingWindowComplete>(&app);
  358. tracing::info!("Main and loading windows created");
  359. // SQLite migration handling:
  360. // We only do this if the sqlite db doesn't exist, and we're expecting the sidecar to create it
  361. // First, we spawn a task that listens for SqliteMigrationProgress events that can
  362. // come from any invocation of the sidecar CLI. The progress is captured by a stdout stream interceptor.
  363. // Then in the loading task, we wait for sqlite migration to complete before
  364. // starting our health check against the server, otherwise long migrations could result in a timeout.
  365. let needs_sqlite_migration = !sqlite_file_exists();
  366. let sqlite_done = needs_sqlite_migration.then(|| {
  367. tracing::info!(
  368. path = %opencode_db_path().expect("failed to get db path").display(),
  369. "Sqlite file not found, waiting for it to be generated"
  370. );
  371. let (done_tx, done_rx) = oneshot::channel::<()>();
  372. let done_tx = Arc::new(Mutex::new(Some(done_tx)));
  373. let init_tx = init_tx.clone();
  374. let id = SqliteMigrationProgress::listen(&app, move |e| {
  375. let _ = init_tx.send(InitStep::SqliteWaiting);
  376. if matches!(e.payload, SqliteMigrationProgress::Done)
  377. && let Some(done_tx) = done_tx.lock().unwrap().take()
  378. {
  379. let _ = done_tx.send(());
  380. }
  381. });
  382. let app = app.clone();
  383. tokio::spawn(done_rx.map(async move |_| {
  384. app.unlisten(id);
  385. }))
  386. });
  387. let loading_task = tokio::spawn({
  388. let app = app.clone();
  389. async move {
  390. tracing::info!("Setting up server connection");
  391. let server_connection = setup_server_connection(app.clone()).await;
  392. tracing::info!("Server connection setup");
  393. // we delay spawning this future so that the timeout is created lazily
  394. let cli_health_check = match server_connection {
  395. ServerConnection::CLI {
  396. child,
  397. health_check,
  398. url,
  399. username,
  400. password,
  401. } => {
  402. let app = app.clone();
  403. Some(
  404. async move {
  405. let res = timeout(Duration::from_secs(30), health_check.0).await;
  406. let err = match res {
  407. Ok(Ok(Ok(()))) => None,
  408. Ok(Ok(Err(e))) => Some(e),
  409. Ok(Err(e)) => Some(format!("Health check task failed: {e}")),
  410. Err(_) => Some("Health check timed out".to_string()),
  411. };
  412. if let Some(err) = err {
  413. let _ = child.kill();
  414. return Err(format!(
  415. "Failed to spawn OpenCode Server ({err}). Logs:\n{}",
  416. get_logs()
  417. ));
  418. }
  419. tracing::info!("CLI health check OK");
  420. app.state::<ServerState>().set_child(Some(child));
  421. Ok(ServerReadyData {
  422. url,
  423. username,
  424. password,
  425. is_sidecar: true,
  426. })
  427. }
  428. .map(move |res| {
  429. let _ = server_ready_tx.send(res);
  430. }),
  431. )
  432. }
  433. ServerConnection::Existing { url } => {
  434. let _ = server_ready_tx.send(Ok(ServerReadyData {
  435. url: url.to_string(),
  436. username: None,
  437. password: None,
  438. is_sidecar: false,
  439. }));
  440. None
  441. }
  442. };
  443. tracing::info!("server connection started");
  444. if let Some(cli_health_check) = cli_health_check {
  445. if let Some(sqlite_done_rx) = sqlite_done {
  446. let _ = sqlite_done_rx.await;
  447. }
  448. tokio::spawn(cli_health_check);
  449. }
  450. let _ = server_ready_rx.await;
  451. tracing::info!("Loading task finished");
  452. }
  453. })
  454. .map_err(|_| ())
  455. .shared();
  456. let loading_window = if needs_sqlite_migration
  457. && timeout(Duration::from_secs(1), loading_task.clone())
  458. .await
  459. .is_err()
  460. {
  461. tracing::debug!("Loading task timed out, showing loading window");
  462. let loading_window = LoadingWindow::create(&app).expect("Failed to create loading window");
  463. sleep(Duration::from_secs(1)).await;
  464. Some(loading_window)
  465. } else {
  466. tracing::debug!("Showing main window without loading window");
  467. MainWindow::create(&app).expect("Failed to create main window");
  468. None
  469. };
  470. let _ = loading_task.await;
  471. tracing::info!("Loading done, completing initialisation");
  472. let _ = init_tx.send(InitStep::Done);
  473. if loading_window.is_some() {
  474. loading_window_complete.await;
  475. tracing::info!("Loading window completed");
  476. }
  477. MainWindow::create(&app).expect("Failed to create main window");
  478. if let Some(loading_window) = loading_window {
  479. let _ = loading_window.close();
  480. }
  481. }
  482. fn setup_app(app: &tauri::AppHandle, init_rx: watch::Receiver<InitStep>) {
  483. #[cfg(any(target_os = "linux", all(debug_assertions, windows)))]
  484. app.deep_link().register_all().ok();
  485. app.manage(InitState { current: init_rx });
  486. }
  487. fn spawn_cli_sync_task(app: AppHandle) {
  488. tokio::spawn(async move {
  489. if let Err(e) = sync_cli(app) {
  490. tracing::error!("Failed to sync CLI: {e}");
  491. }
  492. });
  493. }
  494. enum ServerConnection {
  495. Existing {
  496. url: String,
  497. },
  498. CLI {
  499. url: String,
  500. username: Option<String>,
  501. password: Option<String>,
  502. child: CommandChild,
  503. health_check: server::HealthCheck,
  504. },
  505. }
  506. async fn setup_server_connection(app: AppHandle) -> ServerConnection {
  507. let custom_url = get_saved_server_url(&app).await;
  508. tracing::info!(?custom_url, "Attempting server connection");
  509. if let Some(url) = &custom_url
  510. && server::check_health_or_ask_retry(&app, url).await
  511. {
  512. tracing::info!(%url, "Connected to custom server");
  513. // If the default server is already local, no need to also spawn a sidecar
  514. if server::is_localhost_url(url) {
  515. return ServerConnection::Existing { url: url.clone() };
  516. }
  517. // Remote default server: fall through and also spawn a local sidecar
  518. }
  519. let local_port = get_sidecar_port();
  520. let hostname = "127.0.0.1";
  521. let local_url = format!("http://{hostname}:{local_port}");
  522. tracing::debug!(url = %local_url, "Checking health of local server");
  523. if server::check_health(&local_url, None).await {
  524. tracing::info!(url = %local_url, "Health check OK, using existing server");
  525. return ServerConnection::Existing { url: local_url };
  526. }
  527. let password = uuid::Uuid::new_v4().to_string();
  528. tracing::info!("Spawning new local server");
  529. let (child, health_check) =
  530. server::spawn_local_server(app, hostname.to_string(), local_port, password.clone());
  531. ServerConnection::CLI {
  532. url: local_url,
  533. username: Some("opencode".to_string()),
  534. password: Some(password),
  535. child,
  536. health_check,
  537. }
  538. }
  539. fn get_sidecar_port() -> u32 {
  540. option_env!("OPENCODE_PORT")
  541. .map(|s| s.to_string())
  542. .or_else(|| std::env::var("OPENCODE_PORT").ok())
  543. .and_then(|port_str| port_str.parse().ok())
  544. .unwrap_or_else(|| {
  545. TcpListener::bind("127.0.0.1:0")
  546. .expect("Failed to bind to find free port")
  547. .local_addr()
  548. .expect("Failed to get local address")
  549. .port()
  550. }) as u32
  551. }
  552. fn sqlite_file_exists() -> bool {
  553. let Ok(path) = opencode_db_path() else {
  554. return true;
  555. };
  556. path.exists()
  557. }
  558. fn opencode_db_path() -> Result<PathBuf, &'static str> {
  559. let xdg_data_home = env::var_os("XDG_DATA_HOME").filter(|v| !v.is_empty());
  560. let data_home = match xdg_data_home {
  561. Some(v) => PathBuf::from(v),
  562. None => {
  563. let home = dirs::home_dir().ok_or("cannot determine home directory")?;
  564. home.join(".local").join("share")
  565. }
  566. };
  567. Ok(data_home.join("opencode").join("opencode.db"))
  568. }
  569. // Creates a `once` listener for the specified event and returns a future that resolves
  570. // when the listener is fired.
  571. // Since the future creation and awaiting can be done separately, it's possible to create the listener
  572. // synchronously before doing something, then awaiting afterwards.
  573. fn event_once_fut<T: tauri_specta::Event + serde::de::DeserializeOwned>(
  574. app: &AppHandle,
  575. ) -> impl Future<Output = ()> {
  576. let (tx, rx) = oneshot::channel();
  577. T::once(app, |_| {
  578. let _ = tx.send(());
  579. });
  580. async {
  581. let _ = rx.await;
  582. }
  583. }