diff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.yml index 7b93d117f9e..c95c402038b 100644 --- a/.github/workflows/desktop-release.yml +++ b/.github/workflows/desktop-release.yml @@ -794,7 +794,8 @@ jobs: "Cap.exe", "cap-muxer.exe", "cap-cli.exe", "avcodec-61.dll", "avdevice-61.dll", "avfilter-10.dll", "avformat-61.dll", "avutil-59.dll", "postproc-58.dll", "swresample-5.dll", "swscale-8.dll", - "dxcompiler.dll", "dxil.dll", "onnxruntime.dll", "onnxruntime_providers_shared.dll" + "dxcompiler.dll", "dxil.dll", "onnxruntime.dll", "onnxruntime_providers_shared.dll", + "msvcp140.dll", "msvcp140_1.dll", "vcruntime140.dll", "vcruntime140_1.dll" ) $forbiddenFiles = @("cap-gpui.exe", "cap-exporter.exe") foreach ($installer in $installers) { diff --git a/apps/desktop-gpui/locales/de.toml b/apps/desktop-gpui/locales/de.toml index b133a1bd897..67ff0fcce13 100644 --- a/apps/desktop-gpui/locales/de.toml +++ b/apps/desktop-gpui/locales/de.toml @@ -3212,6 +3212,13 @@ quit_anyway = "Trotzdem beenden" still_open = "Cap ist noch geöffnet" unconfirmed = "Beenden abgebrochen, weil nicht bestätigt werden konnte, dass die Aufnahme beendet wurde. Cap bleibt geöffnet. Verwenden Sie „Stoppen“ und beenden Sie Cap dann erneut." +[dialog.startup] +failed = "{error}\n\nDetails wurden in {folder} gespeichert." +failed_title = "Cap konnte nicht gestartet werden" +quit_and_reopen = "Beenden und neu öffnen" +unresponsive = "Cap läuft bereits, reagiert aber nicht. Diese Instanz beenden und Cap neu öffnen?" +unresponsive_title = "Cap reagiert nicht" + [dialog.update] already_getting = "Cap bereitet Version {version} bereits vor." available = "Version {version} von Cap ist verfügbar. Cap lädt sie im Hintergrund herunter und informiert Sie, sobald sie installiert werden kann." diff --git a/apps/desktop-gpui/locales/en.toml b/apps/desktop-gpui/locales/en.toml index 84a31e6c100..f4497813b0f 100644 --- a/apps/desktop-gpui/locales/en.toml +++ b/apps/desktop-gpui/locales/en.toml @@ -3214,6 +3214,13 @@ quit_anyway = "Quit Anyway" still_open = "Cap is still open" unconfirmed = "Quit canceled because recording shutdown could not be confirmed. Cap will stay open. Use Stop, then try Quit again." +[dialog.startup] +failed = { text = "{error}\n\nDetails were saved in {folder}.", context = "{error} is a technical reason, usually in English. {folder} is a folder path." } +failed_title = "Cap couldn't start" +quit_and_reopen = { text = "Quit and Reopen", context = "Button: quit the copy of Cap that is not responding and start a new one." } +unresponsive = "Cap is already running but isn't responding. Quit that copy and open Cap again?" +unresponsive_title = "Cap isn't responding" + [dialog.update] already_getting = { text = "Cap is already getting version {version} ready.", context = "{version} is a version number such as 0.6.2." } available = { text = "Version {version} of Cap is available. Cap will download it in the background and let you know when it's ready to install.", context = "{version} is a version number such as 0.6.2." } diff --git a/apps/desktop-gpui/locales/es.toml b/apps/desktop-gpui/locales/es.toml index e47aaa02153..89d008800a7 100644 --- a/apps/desktop-gpui/locales/es.toml +++ b/apps/desktop-gpui/locales/es.toml @@ -3212,6 +3212,13 @@ quit_anyway = "Salir de todos modos" still_open = "Cap sigue abierto" unconfirmed = "Se canceló la salida porque no se pudo confirmar que la grabación se detuviera. Cap seguirá abierto. Usa Detener y vuelve a intentar salir." +[dialog.startup] +failed = "{error}\n\nLos detalles se guardaron en {folder}." +failed_title = "Cap no pudo iniciarse" +quit_and_reopen = "Salir y volver a abrir" +unresponsive = "Cap ya se está ejecutando, pero no responde. ¿Quieres cerrar esa copia y volver a abrir Cap?" +unresponsive_title = "Cap no responde" + [dialog.update] already_getting = "Cap ya está preparando la versión {version}." available = "La versión {version} de Cap está disponible. Cap la descargará en segundo plano y te avisará cuando esté lista para instalarse." diff --git a/apps/desktop-gpui/locales/fr.toml b/apps/desktop-gpui/locales/fr.toml index 130e417653d..3f59da14f31 100644 --- a/apps/desktop-gpui/locales/fr.toml +++ b/apps/desktop-gpui/locales/fr.toml @@ -3212,6 +3212,13 @@ quit_anyway = "Quitter quand même" still_open = "Cap est toujours ouvert" unconfirmed = "Fermeture annulée, car l'arrêt de l'enregistrement n'a pas pu être confirmé. Cap reste ouvert. Utilisez Arrêter, puis quittez à nouveau." +[dialog.startup] +failed = "{error}\n\nLes détails ont été enregistrés dans {folder}." +failed_title = "Cap n'a pas pu démarrer" +quit_and_reopen = "Quitter et rouvrir" +unresponsive = "Cap est déjà ouvert mais ne répond pas. Quitter cette instance et rouvrir Cap ?" +unresponsive_title = "Cap ne répond pas" + [dialog.update] already_getting = "Cap prépare déjà la version {version}." available = "La version {version} de Cap est disponible. Cap la télécharge en arrière-plan et vous prévient quand elle est prête à être installée." diff --git a/apps/desktop-gpui/locales/hi.toml b/apps/desktop-gpui/locales/hi.toml index 679436881aa..8aaf6d08f92 100644 --- a/apps/desktop-gpui/locales/hi.toml +++ b/apps/desktop-gpui/locales/hi.toml @@ -3212,6 +3212,13 @@ quit_anyway = "फिर भी बंद करें" still_open = "Cap अभी भी खुला है" unconfirmed = "रिकॉर्डिंग बंद होने की पुष्टि नहीं हो सकी, इसलिए बाहर निकलना रद्द किया गया। Cap खुला रहेगा। रोकें का इस्तेमाल करें, फिर दोबारा बाहर निकलने की कोशिश करें।" +[dialog.startup] +failed = "{error}\n\nविवरण {folder} में सहेजे गए हैं।" +failed_title = "Cap शुरू नहीं हो सका" +quit_and_reopen = "बंद करें और फिर से खोलें" +unresponsive = "Cap पहले से चल रहा है लेकिन जवाब नहीं दे रहा है। उसे बंद करके Cap फिर से खोलें?" +unresponsive_title = "Cap जवाब नहीं दे रहा है" + [dialog.update] already_getting = "Cap पहले से ही वर्ज़न {version} तैयार कर रहा है।" available = "Cap का वर्ज़न {version} उपलब्ध है। Cap इसे बैकग्राउंड में डाउनलोड करेगा और इंस्टॉल के लिए तैयार होने पर आपको बताएगा।" diff --git a/apps/desktop-gpui/locales/ja.toml b/apps/desktop-gpui/locales/ja.toml index 13b8e54ec74..fc60571c0a0 100644 --- a/apps/desktop-gpui/locales/ja.toml +++ b/apps/desktop-gpui/locales/ja.toml @@ -3212,6 +3212,13 @@ quit_anyway = "それでも終了" still_open = "Capはまだ開いています" unconfirmed = "録画の停止を確認できなかったため、終了をキャンセルしました。Capは開いたままになります。「停止」を使ってから、もう一度終了してください。" +[dialog.startup] +failed = "{error}\n\n詳細は{folder}に保存されました。" +failed_title = "Capを起動できませんでした" +quit_and_reopen = "終了して再度開く" +unresponsive = "Capはすでに起動していますが、応答していません。そのCapを終了して、もう一度開きますか?" +unresponsive_title = "Capが応答していません" + [dialog.update] already_getting = "Capはすでにバージョン{version}を準備しています。" available = "Capのバージョン{version}が利用可能です。バックグラウンドでダウンロードし、インストールの準備ができたらお知らせします。" diff --git a/apps/desktop-gpui/locales/zh-CN.toml b/apps/desktop-gpui/locales/zh-CN.toml index f71059f3cf5..8b2e7ca527c 100644 --- a/apps/desktop-gpui/locales/zh-CN.toml +++ b/apps/desktop-gpui/locales/zh-CN.toml @@ -3212,6 +3212,13 @@ quit_anyway = "仍然退出" still_open = "Cap 仍在运行" unconfirmed = "无法确认录制已停止,已取消退出。Cap 将保持打开。请点击“停止”,然后再次尝试退出。" +[dialog.startup] +failed = "{error}\n\n详细信息已保存在 {folder}。" +failed_title = "Cap 无法启动" +quit_and_reopen = "退出并重新打开" +unresponsive = "Cap 已在运行,但没有响应。要退出它并重新打开 Cap 吗?" +unresponsive_title = "Cap 没有响应" + [dialog.update] already_getting = "Cap 已在准备版本 {version}。" available = "Cap {version} 版本现已推出。Cap 会在后台下载,并在可以安装时通知你。" diff --git a/apps/desktop-gpui/packaging/windows/installer-hooks.nsh b/apps/desktop-gpui/packaging/windows/installer-hooks.nsh index f696c1c5ffe..06c93ec885d 100644 --- a/apps/desktop-gpui/packaging/windows/installer-hooks.nsh +++ b/apps/desktop-gpui/packaging/windows/installer-hooks.nsh @@ -18,12 +18,48 @@ SetCompressorDictSize 128 Pop $0 !macroend +; Any other cap-cli.exe or cap-muxer.exe running from this install holds the +; FFmpeg DLLs open. Copying over them failed with an Abort, Retry, Ignore +; prompt after Cap.exe was already replaced, so Abort or Ignore left a mix of +; versions on disk (and a silent install skipped the files). Nothing is copied +; until they have exited: the check waits up to 10 seconds, then asks the user +; to stop them, and a silent install or Cancel stops before any file changes. +; Starting PowerShell costs seconds, so it only runs when a process with either +; name exists. Exit code 2 means one from this install is still running; any +; other failure of the check keeps the previous behaviour of going ahead. +!macro WaitForCapCommandLineTools ABORT_TEXT + !define CapToolsCheck cap_tools_check_${__LINE__} + Push $0 + Push $1 + System::Call 'kernel32::SetEnvironmentVariable(t "CAP_INSTALL_DIR", t "$INSTDIR")i' + ${CapToolsCheck}: + nsis_tauri_utils::FindProcessCurrentUser "cap-cli.exe" + Pop $0 + ${If} $0 != 0 + nsis_tauri_utils::FindProcessCurrentUser "cap-muxer.exe" + Pop $0 + ${EndIf} + ${If} $0 = 0 + nsExec::ExecToStack `"$SYSDIR\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command "try { $$dir = [IO.Path]::GetFullPath($$env:CAP_INSTALL_DIR).TrimEnd('\'); $$deadline = (Get-Date).AddSeconds(10); do { $$running = @(Get-CimInstance Win32_Process -ErrorAction Stop | Where-Object { ($$_.Name -eq 'cap-cli.exe' -or $$_.Name -eq 'cap-muxer.exe') -and $$_.ExecutablePath -and ([IO.Path]::GetDirectoryName($$_.ExecutablePath) -eq $$dir) }); if ($$running.Count -eq 0) { exit 0 }; Start-Sleep -Milliseconds 500 } while ((Get-Date) -lt $$deadline); exit 2 } catch { exit 0 }"` + Pop $0 + Pop $1 + ${If} $0 == 2 + MessageBox MB_RETRYCANCEL|MB_ICONEXCLAMATION "Cap's command line tool is still running, for example a recording started with cap record or an export. Stop it, then click Retry." /SD IDCANCEL IDRETRY ${CapToolsCheck} + Abort "${ABORT_TEXT}" + ${EndIf} + ${EndIf} + Pop $1 + Pop $0 + !undef CapToolsCheck +!macroend + ; Cap 0.6.0 ran its GPUI app as cap-gpui.exe next to Cap.exe. The template ; only closes Cap.exe before copying files, so a running cap-gpui.exe would keep ; the shared FFmpeg DLLs locked and stop the update with a file-in-use error. !macro NSIS_HOOK_PREINSTALL !insertmacro CheckIfAppIsRunning "cap-gpui.exe" "${PRODUCTNAME}" !insertmacro EndCapMcpServers + !insertmacro WaitForCapCommandLineTools "Cap was not updated because its command line tool is still running." !macroend !macro NSIS_HOOK_POSTINSTALL @@ -34,4 +70,5 @@ SetCompressorDictSize 128 !macro NSIS_HOOK_PREUNINSTALL !insertmacro EndCapMcpServers + !insertmacro WaitForCapCommandLineTools "Cap was not uninstalled because its command line tool is still running." !macroend diff --git a/apps/desktop-gpui/src/crash_capture.rs b/apps/desktop-gpui/src/crash_capture.rs index 9008f1d53ab..eedd7d8b833 100644 --- a/apps/desktop-gpui/src/crash_capture.rs +++ b/apps/desktop-gpui/src/crash_capture.rs @@ -298,6 +298,12 @@ fn record(text: &str) { } } +/// Written straight to the crash record: a failed launch exits before the +/// tracing queue drains. +pub fn record_startup_failure(error: &str) { + record(&format!("{} startup failed: {error}\n", now())); +} + const PREVIOUS_SESSION_ENDED: &str = "previous session ended without a clean quit"; /// The previous session's marker and, when there is one, the crash record @@ -358,6 +364,7 @@ fn install_panic_hook() { now() )); tracing::error!(%thread, %location, %message, "panic"); + crate::startup::report_panic(&message, &location); previous(info); })); } diff --git a/apps/desktop-gpui/src/i18n/dialogs_surface_tests.rs b/apps/desktop-gpui/src/i18n/dialogs_surface_tests.rs index 39be8a23156..b3686bac18d 100644 --- a/apps/desktop-gpui/src/i18n/dialogs_surface_tests.rs +++ b/apps/desktop-gpui/src/i18n/dialogs_surface_tests.rs @@ -56,6 +56,7 @@ const FORMATTED: &[&str] = &[ "transcription.download.file_progress", "transcription.download.progress", "dialog.quit.canceled", + "dialog.startup.failed", "dialog.update.already_getting", "dialog.update.available", "dialog.update.check_failed", @@ -836,6 +837,16 @@ fn dialog_surfaces_match_the_literals_they_replaced() { "The Recommended and High Accuracy models only transcribe English and 24 other European languages. Download the Small or Medium model to caption this language", ), (tr::dialog::quit::still_open(), "Cap is still open"), + (tr::dialog::startup::failed_title(), "Cap couldn't start"), + (tr::dialog::startup::quit_and_reopen(), "Quit and Reopen"), + ( + tr::dialog::startup::unresponsive(), + "Cap is already running but isn't responding. Quit that copy and open Cap again?", + ), + ( + tr::dialog::startup::unresponsive_title(), + "Cap isn't responding", + ), ( tr::dialog::quit::files_kept(), "Everything recorded so far stays in the recording's folder.", @@ -1177,6 +1188,10 @@ fn update_and_quit_messages_format_like_the_code_they_replaced() { tr::dialog::update::failed(error), format!("{error}\n\nYou can always download the latest version from Cap.so/download."), ), + ( + tr::dialog::startup::failed(error, "C:\\logs"), + format!("{error}\n\nDetails were saved in C:\\logs."), + ), ]; for (translated, literal) in pairs { assert_eq!(translated, literal); diff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rs index 69baaee46c1..67f78102e90 100644 --- a/apps/desktop-gpui/src/main.rs +++ b/apps/desktop-gpui/src/main.rs @@ -101,6 +101,7 @@ mod sign_in; mod single_instance; #[cfg(debug_assertions)] mod snapshot; +mod startup; mod store; mod target_overlay; mod target_thumbnails; @@ -338,7 +339,7 @@ fn main() { std::process::exit(status); } - let _log_guard = init_logging(); + startup::begin(init_logging()); crash_capture::install(&diagnostics::logs_dir()); #[cfg(target_os = "linux")] if let Some(wayland_display) = stale_wayland_display { @@ -479,11 +480,10 @@ fn main() { move |window, cx| cx.new(|cx| MainWindow::new(session, window, cx)) }, ) - .inspect_err(|error| tracing::error!("failed to open the main window: {error:#}")); - let Ok(window_handle) = window_handle else { - cx.quit(); - return; - }; + .unwrap_or_else(|error| { + startup::fail(format!("The main window could not be opened: {error:#}")) + }); + startup::finished(); cx.on_app_quit(|_| async { crash_capture::mark_clean_exit(); @@ -846,6 +846,7 @@ fn main() { } }); runtime.shutdown_background(); + startup::flush_log(); } #[cfg(all( diff --git a/apps/desktop-gpui/src/single_instance.rs b/apps/desktop-gpui/src/single_instance.rs index f08ded5b676..11d1c98e15c 100644 --- a/apps/desktop-gpui/src/single_instance.rs +++ b/apps/desktop-gpui/src/single_instance.rs @@ -42,40 +42,32 @@ pub fn acquire() { activate_macos_instance, ) { Ok(Some(lock)) => lock, - Ok(None) => std::process::exit(0), + Ok(None) => crate::startup::exit(0), Err(error) => { - tracing::error!(%error, "Could not acquire the Cap GPUI instance lock"); - std::process::exit(1); + crate::startup::fail(format!("Could not acquire the Cap instance lock: {error}")) } }; if INSTANCE_LOCK.set(lock).is_err() { - tracing::error!("The Cap GPUI instance lock was initialized twice"); - std::process::exit(1); + crate::startup::fail("The Cap instance lock was initialized twice."); } if let Err(error) = publish_macos_pidfile(&path) { - tracing::error!(%error, "Could not publish the Cap GPUI instance pidfile"); - std::process::exit(1); + crate::startup::fail(format!( + "Could not publish the Cap instance pidfile: {error}" + )); } } #[cfg(windows)] - acquire_windows_instance(&path); + let _launch_lock = acquire_windows_instance(&path); #[cfg(target_os = "linux")] - if let Ok(raw) = std::fs::read_to_string(&path) - && let Ok(pid) = raw.trim().parse::() - && pid > 0 - && pid != std::process::id() as i32 - && is_cap_gpui(pid) - { - match forward_linux_reopen(&path, pid as u32) { - Ok(()) => tracing::info!(pid, "Requested the existing Cap GPUI controls"), - Err(error) => tracing::warn!( - pid, - %error, - "Could not reopen Cap GPUI; the existing instance remains unchanged" - ), - } - std::process::exit(0); - } + let _launch_lock = match acquire_linux_instance( + &path, + |pid| forward_linux_reopen(&path, pid), + crate::startup::confirm_quit_unresponsive, + ) { + Ok(LinuxLaunch::HandedOff | LinuxLaunch::Cancelled) => crate::startup::exit(0), + Ok(LinuxLaunch::Start(lock)) => lock, + Err(error) => crate::startup::fail(error), + }; #[cfg(not(target_os = "macos"))] { if let Some(parent) = path.parent() { @@ -88,15 +80,196 @@ pub fn acquire() { #[cfg(target_os = "linux")] if let Err(error) = start_linux_reopen(&path) { - tracing::error!(%error, "could not start Cap GPUI activation"); - std::process::exit(1); + crate::startup::fail(format!("Could not start Cap activation: {error}")); } #[cfg(target_os = "macos")] if let Err(error) = start_deep_link_forwarding(&path) { - tracing::error!(%error, "could not start Cap GPUI deep-link forwarding"); - std::process::exit(1); + crate::startup::fail(format!("Could not start Cap deep-link forwarding: {error}")); + } +} + +#[cfg(target_os = "linux")] +#[derive(Debug)] +enum LinuxLaunch { + HandedOff, + Cancelled, + /// Held until this launch has published its pidfile and activation + /// socket, so the next launch finds them instead of a stale pid. + Start(std::fs::File), +} + +/// Launches of one profile take turns through an exclusive lock, so two of +/// them can never both end the same hung copy and both carry on. Every pass +/// repeats the hand-off, so a copy that recovered or exited while the prompt +/// was open is never ended, and only the exact process the user confirmed is. +/// The pidfd is taken before the prompt, so however long the prompt stays up +/// a reused pid can never receive the signal. A launch that waits on the lock +/// while another launch shows the prompt then hands off to whichever copy +/// that prompt leaves running. +#[cfg(target_os = "linux")] +fn acquire_linux_instance( + path: &Path, + mut forward: impl FnMut(u32) -> std::io::Result<()>, + mut confirm: impl FnMut() -> bool, +) -> Result { + let lock = lock_linux_launch(path) + .map_err(|error| format!("Could not acquire the Cap instance lock: {error}"))?; + let mut confirmed: Option<(u32, LinuxProcess)> = None; + let mut ended = None; + loop { + let Some(pid) = running_linux_instance(path) else { + return Ok(LinuxLaunch::Start(lock)); + }; + match forward(pid) { + Ok(()) => { + tracing::info!(pid, "Requested the existing Cap GPUI controls"); + return Ok(LinuxLaunch::HandedOff); + } + Err(error) => { + tracing::warn!(pid, %error, "The running Cap GPUI did not answer the reopen request") + } + } + let confirmed_pid = confirmed.as_ref().map(|(pid, _)| *pid); + match takeover_step(pid, confirmed_pid, ended) { + TakeoverStep::Ask => { + let process = match LinuxProcess::open(pid as i32) { + Ok(process) => process, + Err(error) if error.raw_os_error() == Some(libc::ESRCH) => continue, + Err(error) => { + return Err(format!( + "Another copy of Cap (process {pid}) is running but isn't responding, and it could not be checked: {error}" + )); + } + }; + if !is_cap_gpui(pid as i32) { + continue; + } + if !confirm() { + return Ok(LinuxLaunch::Cancelled); + } + confirmed = Some((pid, process)); + } + TakeoverStep::End => { + let Some((_, process)) = confirmed.take() else { + continue; + }; + if !end_linux_instance(&process) { + return Err(format!( + "The copy of Cap that isn't responding (process {pid}) could not be quit." + )); + } + tracing::info!(pid, "ended the unresponsive Cap GPUI"); + ended = Some(pid); + } + TakeoverStep::GiveUp => { + return Err(format!( + "The copy of Cap that isn't responding (process {pid}) could not be quit." + )); + } + } + } +} + +#[cfg(target_os = "linux")] +fn running_linux_instance(path: &Path) -> Option { + let pid = std::fs::read_to_string(path) + .ok()? + .trim() + .parse::() + .ok()?; + (pid > 0 && pid != std::process::id() as i32 && is_cap_gpui(pid)).then_some(pid as u32) +} + +#[cfg(target_os = "linux")] +fn lock_linux_launch(path: &Path) -> std::io::Result { + use std::os::{fd::AsRawFd, unix::fs::OpenOptionsExt}; + + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + let file = std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW) + .open(path.with_extension("lock"))?; + loop { + if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) } == 0 { + return Ok(file); + } + let error = std::io::Error::last_os_error(); + if error.kind() != std::io::ErrorKind::Interrupted { + return Err(error); + } + } +} + +#[cfg(target_os = "linux")] +struct LinuxProcess(std::os::fd::OwnedFd); + +#[cfg(target_os = "linux")] +impl LinuxProcess { + fn open(pid: i32) -> std::io::Result { + use std::os::fd::FromRawFd; + + let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, pid, 0) }; + if fd < 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(Self(unsafe { + std::os::fd::OwnedFd::from_raw_fd(fd as i32) + })) + } + + fn signal(&self, signal: libc::c_int) -> std::io::Result<()> { + use std::os::fd::AsRawFd; + + let sent = unsafe { + libc::syscall( + libc::SYS_pidfd_send_signal, + self.0.as_raw_fd(), + signal, + std::ptr::null::(), + 0, + ) + }; + if sent == 0 { + Ok(()) + } else { + Err(std::io::Error::last_os_error()) + } + } + + fn exited_within(&self, timeout: std::time::Duration) -> bool { + use std::os::fd::AsRawFd; + + let mut poll = libc::pollfd { + fd: self.0.as_raw_fd(), + events: libc::POLLIN, + revents: 0, + }; + let ready = unsafe { libc::poll(&mut poll, 1, timeout.as_millis() as libc::c_int) }; + ready > 0 + } +} + +#[cfg(target_os = "linux")] +fn end_linux_instance(process: &LinuxProcess) -> bool { + let limit = std::time::Duration::from_secs(3); + for signal in [libc::SIGTERM, libc::SIGKILL] { + match process.signal(signal) { + Ok(()) => {} + Err(error) if error.raw_os_error() == Some(libc::ESRCH) => return true, + Err(_) => return false, + } + if process.exited_within(limit) { + return true; + } } + false } /// Linux zombies retain their comm name but lose their exe link. @@ -1032,8 +1205,10 @@ pub fn init_linux_reopen(cx: &mut gpui::App) { .detach(); } +/// Held until this launch has published its pidfile and endpoint, so the next +/// launch finds them instead of a stale pid. #[cfg(windows)] -fn acquire_windows_instance(path: &Path) { +fn acquire_windows_instance(path: &Path) -> WindowsLaunchLock { use std::hash::{Hash, Hasher}; use windows_sys::Win32::{ Foundation::{CloseHandle, ERROR_ALREADY_EXISTS, GetLastError}, @@ -1042,52 +1217,241 @@ fn acquire_windows_instance(path: &Path) { let mut hasher = std::collections::hash_map::DefaultHasher::new(); path.hash(&mut hasher); - let name = format!("Local\\CapGpui-{:016x}", hasher.finish()) + let profile = format!("{:016x}", hasher.finish()); + let launch_lock = match lock_windows_launch(&format!("Local\\CapGpuiLaunch-{profile}")) { + Ok(lock) => lock, + Err(error) => { + crate::startup::fail(format!("Could not acquire the Cap instance lock: {error}")) + } + }; + let name = format!("Local\\CapGpui-{profile}") .encode_utf16() .chain(std::iter::once(0)) .collect::>(); - let mutex = unsafe { CreateMutexW(std::ptr::null(), 0, name.as_ptr()) }; - let last_error = unsafe { GetLastError() }; - if mutex.is_null() { - tracing::error!( - error = last_error, - "could not acquire the Cap GPUI instance mutex" - ); - std::process::exit(1); - } + let mut confirmed = None; + let mut ended = None; + let mutex = loop { + let mutex = unsafe { CreateMutexW(std::ptr::null(), 0, name.as_ptr()) }; + let last_error = unsafe { GetLastError() }; + if mutex.is_null() { + crate::startup::fail(format!( + "Could not create the Cap instance mutex (Windows error {last_error})." + )); + } + if last_error != ERROR_ALREADY_EXISTS { + break mutex; + } - if last_error == ERROR_ALREADY_EXISTS { - for _ in 0..40 { - if let Some(pid) = windows_instance_pid(path) { - tracing::info!(pid, "Cap GPUI is already running; bringing it forward"); - if forward_windows_deep_links(path, pid) { - activate_windows_instance(pid); - } else if let Err(error) = reopen_windows_instance(path, pid) { - tracing::warn!(%error, "could not reopen the running Cap GPUI"); - activate_windows_instance(pid); + let handed_off = hand_off_to_windows_instance(path); + let _ = unsafe { CloseHandle(mutex) }; + let pid = match handed_off { + Ok(()) => crate::startup::exit(0), + Err(Some(pid)) => pid, + Err(None) => crate::startup::fail( + "Another copy of Cap is running but could not be reached. End Cap in Task Manager, then open it again.", + ), + }; + match takeover_step(pid, confirmed, ended) { + TakeoverStep::Ask => { + tracing::warn!(pid, "the running Cap GPUI is not responding"); + if !crate::startup::confirm_quit_unresponsive() { + crate::startup::exit(0); } - break; + confirmed = Some(pid); } - std::thread::sleep(std::time::Duration::from_millis(50)); + TakeoverStep::End => { + match end_windows_process(pid) { + Ok(()) => tracing::info!(pid, "ended the unresponsive Cap GPUI"), + Err(error) => { + tracing::warn!(pid, %error, "could not end the unresponsive Cap GPUI") + } + } + ended = Some(pid); + } + TakeoverStep::GiveUp => crate::startup::fail(format!( + "The copy of Cap that isn't responding (process {pid}) could not be quit. Restart your computer, then open Cap again." + )), } - - let _ = unsafe { CloseHandle(mutex) }; - std::process::exit(0); - } + }; if INSTANCE_MUTEX.set(mutex as usize).is_err() { let _ = unsafe { CloseHandle(mutex) }; - tracing::error!("the Cap GPUI instance mutex was initialized twice"); - std::process::exit(1); + crate::startup::fail("The Cap instance mutex was initialized twice."); } if let Err(error) = start_deep_link_forwarding(path) { - tracing::error!(%error, "could not start Cap GPUI deep-link forwarding"); - std::process::exit(1); + crate::startup::fail(format!("Could not start Cap deep-link forwarding: {error}")); + } + launch_lock +} + +/// Launches of one profile take turns through this lock, and only the holder +/// opens the instance mutex. A launch still checking on a frozen copy would +/// otherwise keep that mutex alive after another launch ended the copy, so +/// both would find it taken with nobody behind it and stop. A launch that +/// dies while holding the lock leaves it abandoned, which counts as free. +#[cfg(windows)] +struct WindowsLaunchLock(windows_sys::Win32::Foundation::HANDLE); + +#[cfg(windows)] +impl Drop for WindowsLaunchLock { + fn drop(&mut self) { + use windows_sys::Win32::{Foundation::CloseHandle, System::Threading::ReleaseMutex}; + + unsafe { + ReleaseMutex(self.0); + CloseHandle(self.0); + } + } +} + +#[cfg(windows)] +fn lock_windows_launch(name: &str) -> std::io::Result { + use windows_sys::Win32::{ + Foundation::{CloseHandle, WAIT_ABANDONED, WAIT_OBJECT_0}, + System::Threading::{CreateMutexW, INFINITE, WaitForSingleObject}, + }; + + let name = name + .encode_utf16() + .chain(std::iter::once(0)) + .collect::>(); + let mutex = unsafe { CreateMutexW(std::ptr::null(), 0, name.as_ptr()) }; + if mutex.is_null() { + return Err(std::io::Error::last_os_error()); + } + match unsafe { WaitForSingleObject(mutex, INFINITE) } { + WAIT_OBJECT_0 | WAIT_ABANDONED => Ok(WindowsLaunchLock(mutex)), + _ => { + let error = std::io::Error::last_os_error(); + let _ = unsafe { CloseHandle(mutex) }; + Err(error) + } } } +#[cfg(any(windows, target_os = "linux", test))] +#[derive(Debug, PartialEq, Eq)] +enum TakeoverStep { + Ask, + End, + GiveUp, +} + +/// Every pass re-takes the lock and repeats the hand-off, so a copy that +/// recovered or exited while the prompt was open is never ended, and only the +/// exact process the user confirmed is. +#[cfg(any(windows, target_os = "linux", test))] +fn takeover_step(pid: u32, confirmed: Option, ended: Option) -> TakeoverStep { + if ended == Some(pid) { + TakeoverStep::GiveUp + } else if confirmed == Some(pid) { + TakeoverStep::End + } else { + TakeoverStep::Ask + } +} + +/// How long a window may go without handling messages before it counts as +/// frozen: the same five seconds after which Windows itself marks a window +/// "Not Responding". +#[cfg(windows)] +const WINDOW_RESPONSE_TIMEOUT_MS: u32 = 5000; + +/// `Err` carries the running instance's pid when one was identified. A +/// failed reopen means the instance's listener thread is stuck; activating +/// its window then showed nothing and the new launch exited without a trace. +/// The listener acknowledges from its own thread, so an acknowledged reopen +/// still needs a window that answers messages: a frozen main thread would +/// otherwise swallow the request just as silently. A Cap whose window answers +/// (including a build without the reopen endpoint) is activated as before. +#[cfg(windows)] +fn hand_off_to_windows_instance(path: &Path) -> Result<(), Option> { + let mut identified = None; + for _ in 0..40 { + identified = windows_instance_pid(path); + if identified.is_some() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(50)); + } + let Some(pid) = identified else { + return Err(None); + }; + tracing::info!(pid, "Cap GPUI is already running; bringing it forward"); + if forward_windows_deep_links(path, pid) { + activate_windows_instance(pid); + return Ok(()); + } + let reopened = reopen_windows_instance(path, pid) + .inspect_err(|error| tracing::warn!(%error, "could not reopen the running Cap GPUI")) + .is_ok(); + match windows_instance_window(pid) { + Some(window) if windows_window_responds(window) => { + if !reopened { + activate_windows_window(window); + } + Ok(()) + } + Some(_) => Err(Some(pid)), + None if reopened => Ok(()), + None => Err(Some(pid)), + } +} + +#[cfg(windows)] +fn windows_window_responds(window: windows_sys::Win32::Foundation::HWND) -> bool { + use windows_sys::Win32::UI::WindowsAndMessaging::{ + SMTO_ABORTIFHUNG, SendMessageTimeoutW, WM_NULL, + }; + + let mut result = 0; + unsafe { + SendMessageTimeoutW( + window, + WM_NULL, + 0, + 0, + SMTO_ABORTIFHUNG, + WINDOW_RESPONSE_TIMEOUT_MS, + &mut result, + ) != 0 + } +} + +#[cfg(windows)] +fn end_windows_process(pid: u32) -> std::io::Result<()> { + use windows_sys::Win32::{ + Foundation::{CloseHandle, WAIT_OBJECT_0}, + System::Threading::{ + OpenProcess, PROCESS_SYNCHRONIZE, PROCESS_TERMINATE, TerminateProcess, + WaitForSingleObject, + }, + }; + + let process = unsafe { OpenProcess(PROCESS_TERMINATE | PROCESS_SYNCHRONIZE, 0, pid) }; + if process.is_null() { + return Err(std::io::Error::last_os_error()); + } + if !windows_process_is_cap(pid) { + let _ = unsafe { CloseHandle(process) }; + return Ok(()); + } + let result = if unsafe { TerminateProcess(process, 1) } == 0 { + Err(std::io::Error::last_os_error()) + } else if unsafe { WaitForSingleObject(process, 5000) } != WAIT_OBJECT_0 { + Err(std::io::Error::new( + std::io::ErrorKind::TimedOut, + "the process did not exit after being ended", + )) + } else { + Ok(()) + }; + let _ = unsafe { CloseHandle(process) }; + result +} + #[cfg(any(windows, target_os = "macos"))] fn start_deep_link_forwarding(path: &Path) -> std::io::Result<()> { use std::hash::BuildHasher; @@ -1328,8 +1692,27 @@ fn read_forwarded_request( Ok(ForwardedRequest::DeepLink(url)) } +/// The pidfile, else the pid in the deep-link endpoint beside it: both live in +/// this profile's app-data folder, the one the instance mutex is named after, +/// so neither can name a Cap running for another profile. #[cfg(windows)] fn windows_instance_pid(path: &Path) -> Option { + let from_pidfile = std::fs::read_to_string(path) + .ok() + .and_then(|contents| contents.trim().parse().ok()); + let from_endpoint = || { + std::fs::read_to_string(path.with_extension("ipc")) + .ok() + .and_then(|contents| parse_forwarding_endpoint(&contents)) + .map(|endpoint| endpoint.pid) + }; + from_pidfile + .filter(|pid| windows_process_is_cap(*pid)) + .or_else(|| from_endpoint().filter(|pid| windows_process_is_cap(*pid))) +} + +#[cfg(windows)] +fn windows_process_is_cap(pid: u32) -> bool { use std::os::windows::ffi::OsStringExt; use windows_sys::Win32::{ Foundation::CloseHandle, @@ -1338,10 +1721,9 @@ fn windows_instance_pid(path: &Path) -> Option { }, }; - let pid = std::fs::read_to_string(path).ok()?.trim().parse().ok()?; let process = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) }; if process.is_null() { - return None; + return false; } let mut image = [0_u16; 1024]; @@ -1349,22 +1731,36 @@ fn windows_instance_pid(path: &Path) -> Option { let found = unsafe { QueryFullProcessImageNameW(process, 0, image.as_mut_ptr(), &mut len) } != 0; let _ = unsafe { CloseHandle(process) }; - if !found { - return None; + found + && is_cap_gpui_image(&PathBuf::from(std::ffi::OsString::from_wide( + &image[..len as usize], + ))) +} + +#[cfg(windows)] +fn activate_windows_instance(pid: u32) { + if let Some(window) = windows_instance_window(pid) { + activate_windows_window(window); } +} - let image = PathBuf::from(std::ffi::OsString::from_wide(&image[..len as usize])); - is_cap_gpui_image(&image).then_some(pid) +#[cfg(windows)] +fn activate_windows_window(window: windows_sys::Win32::Foundation::HWND) { + use windows_sys::Win32::UI::WindowsAndMessaging::{ + SW_RESTORE, SetForegroundWindow, ShowWindow, + }; + + unsafe { + ShowWindow(window, SW_RESTORE); + SetForegroundWindow(window); + } } #[cfg(windows)] -fn activate_windows_instance(pid: u32) { +fn windows_instance_window(pid: u32) -> Option { use windows_sys::Win32::{ Foundation::{BOOL, HWND, LPARAM, TRUE}, - UI::WindowsAndMessaging::{ - EnumWindows, GetWindowThreadProcessId, IsWindowVisible, SW_RESTORE, - SetForegroundWindow, ShowWindow, - }, + UI::WindowsAndMessaging::{EnumWindows, GetWindowThreadProcessId, IsWindowVisible}, }; struct Activation { @@ -1400,12 +1796,7 @@ fn activate_windows_instance(pid: u32) { ); } - if let Some(window) = activation.visible.or(activation.fallback) { - unsafe { - ShowWindow(window, SW_RESTORE); - SetForegroundWindow(window); - } - } + activation.visible.or(activation.fallback) } #[cfg(test)] @@ -1600,7 +1991,18 @@ mod tests { .map(|entry| entry.unwrap().file_name().into_string().unwrap()) .collect::>(); entries.sort(); - assert_eq!(entries, ["acquire-returned", "cap-gpui.pid"]); + // The launch lock stays on disk: removing it would let two launches + // lock different files and both carry on. + assert_eq!( + entries, + ["acquire-returned", "cap-gpui.lock", "cap-gpui.pid"] + ); + let lock = std::fs::metadata(fixture.directory.join("cap-gpui.lock")).unwrap(); + assert_eq!(lock.len(), 0); + assert_eq!( + std::os::unix::fs::PermissionsExt::mode(&lock.permissions()) & 0o777, + 0o600 + ); } #[cfg(target_os = "linux")] @@ -2990,3 +3392,476 @@ mod linux_reopen_tests { } } } + +#[cfg(all(test, windows))] +mod windows_takeover_tests { + use super::*; + use std::time::{Duration, Instant}; + + /// A stand-in for a running Cap: `ping.exe` copied to `Cap.exe`, so its + /// image name is Cap's while it runs headless for as long as a test needs. + struct FakeCap { + directory: tempfile::TempDir, + child: std::process::Child, + } + + impl FakeCap { + fn start() -> Self { + let directory = tempfile::tempdir().unwrap(); + let system = std::env::var_os("SystemRoot").unwrap(); + let image = directory.path().join("Cap.exe"); + std::fs::copy( + PathBuf::from(system).join("System32").join("PING.EXE"), + &image, + ) + .unwrap(); + let child = std::process::Command::new(&image) + .args(["-n", "60", "127.0.0.1"]) + .stdout(std::process::Stdio::null()) + .spawn() + .unwrap(); + Self { directory, child } + } + + fn pid(&self) -> u32 { + self.child.id() + } + + fn pidfile(&self) -> PathBuf { + let path = self.directory.path().join("cap-gpui.pid"); + std::fs::write(&path, self.pid().to_string()).unwrap(); + path + } + } + + impl Drop for FakeCap { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } + } + + fn exited(child: &mut std::process::Child) -> bool { + child.try_wait().unwrap().is_some() + } + + #[test] + fn a_pidfile_naming_a_process_that_is_not_cap_identifies_no_instance() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("cap-gpui.pid"); + std::fs::write(&path, std::process::id().to_string()).unwrap(); + assert_eq!(windows_instance_pid(&path), None); + + let mut gone = std::process::Command::new("cmd") + .args(["/C", "exit"]) + .spawn() + .unwrap(); + let gone_pid = gone.id(); + gone.wait().unwrap(); + std::fs::write(&path, gone_pid.to_string()).unwrap(); + assert_eq!(windows_instance_pid(&path), None); + + std::fs::write(&path, "not a pid").unwrap(); + assert_eq!(windows_instance_pid(&path), None); + } + + #[test] + fn a_held_lock_with_no_identifiable_instance_is_reported() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("cap-gpui.pid"); + std::fs::write(&path, std::process::id().to_string()).unwrap(); + let started = Instant::now(); + assert_eq!(hand_off_to_windows_instance(&path), Err(None)); + assert!(started.elapsed() < Duration::from_secs(5)); + } + + #[test] + fn an_instance_that_never_answers_reopen_is_reported_instead_of_silently_activated() { + let fake = FakeCap::start(); + let path = fake.pidfile(); + let listener = std::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0)).unwrap(); + write_forwarding_endpoint( + &path.with_extension("ipc"), + ForwardingEndpoint { + pid: fake.pid(), + port: listener.local_addr().unwrap().port(), + secret: 7, + }, + ) + .unwrap(); + let started = Instant::now(); + assert_eq!(hand_off_to_windows_instance(&path), Err(Some(fake.pid()))); + assert!(started.elapsed() < Duration::from_secs(8)); + drop(listener); + } + + #[test] + fn an_instance_without_a_reopen_endpoint_or_window_is_reported() { + let fake = FakeCap::start(); + let path = fake.pidfile(); + assert_eq!(hand_off_to_windows_instance(&path), Err(Some(fake.pid()))); + } + + #[test] + fn an_instance_that_acknowledges_reopen_is_handed_off() { + use std::io::{Read, Write}; + + let fake = FakeCap::start(); + let path = fake.pidfile(); + let listener = std::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0)).unwrap(); + let secret = 0x5eed; + write_forwarding_endpoint( + &path.with_extension("ipc"), + ForwardingEndpoint { + pid: fake.pid(), + port: listener.local_addr().unwrap().port(), + secret, + }, + ) + .unwrap(); + let responder = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + let mut header = [0_u8; 12]; + stream.read_exact(&mut header).unwrap(); + assert_eq!(&header[..8], &u64::to_be_bytes(secret)); + assert_eq!(&header[8..], &0_u32.to_be_bytes()); + stream.write_all(&[REOPEN_ACK]).unwrap(); + }); + assert_eq!(hand_off_to_windows_instance(&path), Ok(())); + responder.join().unwrap(); + } + + #[test] + fn the_endpoint_identifies_an_instance_whose_pidfile_is_missing() { + let fake = FakeCap::start(); + let path = fake.directory.path().join("cap-gpui.pid"); + assert_eq!(windows_instance_pid(&path), None); + write_forwarding_endpoint( + &path.with_extension("ipc"), + ForwardingEndpoint { + pid: fake.pid(), + port: 1, + secret: 1, + }, + ) + .unwrap(); + assert_eq!(windows_instance_pid(&path), Some(fake.pid())); + std::fs::write(&path, std::process::id().to_string()).unwrap(); + assert_eq!(windows_instance_pid(&path), Some(fake.pid())); + } + + #[test] + fn ending_an_unresponsive_instance_waits_for_it_to_exit() { + let mut fake = FakeCap::start(); + assert!(windows_process_is_cap(fake.pid())); + end_windows_process(fake.pid()).unwrap(); + assert!(exited(&mut fake.child)); + assert!(!windows_process_is_cap(fake.pid())); + } + + fn launch_lock_name() -> String { + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + format!( + "Local\\CapGpuiLaunchTest-{}-{}", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + ) + } + + #[test] + fn a_second_launch_waits_until_the_first_releases_the_lock() { + let name = launch_lock_name(); + let first = lock_windows_launch(&name).unwrap(); + let (acquired, waiting) = std::sync::mpsc::channel(); + let second = std::thread::spawn({ + let name = name.clone(); + move || { + let lock = lock_windows_launch(&name).unwrap(); + acquired.send(()).unwrap(); + drop(lock); + } + }); + assert!(waiting.recv_timeout(Duration::from_millis(300)).is_err()); + drop(first); + waiting.recv_timeout(Duration::from_secs(5)).unwrap(); + second.join().unwrap(); + } + + #[test] + fn a_launch_that_died_holding_the_lock_does_not_block_the_next() { + let name = launch_lock_name(); + std::thread::spawn({ + let name = name.clone(); + move || std::mem::forget(lock_windows_launch(&name).unwrap()) + }) + .join() + .unwrap(); + let (acquired, waiting) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let lock = lock_windows_launch(&name).unwrap(); + acquired.send(()).unwrap(); + drop(lock); + }); + waiting.recv_timeout(Duration::from_secs(5)).unwrap(); + } + + #[test] + fn a_launch_of_another_profile_never_waits() { + let held = lock_windows_launch(&launch_lock_name()).unwrap(); + let other = launch_lock_name(); + let (acquired, waiting) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let lock = lock_windows_launch(&other).unwrap(); + acquired.send(()).unwrap(); + drop(lock); + }); + waiting.recv_timeout(Duration::from_secs(5)).unwrap(); + drop(held); + } + + #[test] + fn ending_never_touches_a_process_that_is_not_cap() { + let mut other = std::process::Command::new("ping") + .args(["-n", "60", "127.0.0.1"]) + .stdout(std::process::Stdio::null()) + .spawn() + .unwrap(); + end_windows_process(other.id()).unwrap(); + assert!(!exited(&mut other)); + other.kill().unwrap(); + other.wait().unwrap(); + } +} + +#[cfg(all(test, target_os = "linux"))] +mod linux_takeover_tests { + use super::*; + use std::time::{Duration, Instant}; + + #[test] + fn a_hung_instance_is_ended_with_sigterm() { + let mut child = std::process::Command::new("sleep") + .arg("60") + .spawn() + .unwrap(); + let process = LinuxProcess::open(child.id() as i32).unwrap(); + let started = Instant::now(); + assert!(end_linux_instance(&process)); + assert!(started.elapsed() < Duration::from_secs(3)); + child.wait().unwrap(); + } + + #[test] + fn an_instance_that_ignores_sigterm_is_killed() { + let mut child = std::process::Command::new("sh") + .args(["-c", "trap '' TERM; while :; do sleep 1; done"]) + .spawn() + .unwrap(); + std::thread::sleep(Duration::from_millis(200)); + let process = LinuxProcess::open(child.id() as i32).unwrap(); + let started = Instant::now(); + assert!(end_linux_instance(&process)); + assert!(started.elapsed() >= Duration::from_secs(3)); + assert!(started.elapsed() < Duration::from_secs(6)); + child.wait().unwrap(); + } + + /// The pidfd keeps naming the original process: once it has exited, no + /// signal can reach whatever later receives its pid. + #[test] + fn a_process_that_exits_during_the_prompt_is_never_signalled_again() { + let mut child = std::process::Command::new("true").spawn().unwrap(); + let process = LinuxProcess::open(child.id() as i32).unwrap(); + child.wait().unwrap(); + let error = process.signal(libc::SIGTERM).unwrap_err(); + assert_eq!(error.raw_os_error(), Some(libc::ESRCH)); + assert!(end_linux_instance(&process)); + } + + /// A copy of `sleep` named like Cap, so `is_cap_gpui` accepts it. + struct FakeCap(std::process::Child); + + impl FakeCap { + fn start(directory: &Path, name: &str) -> Self { + let image = directory.join(name).join("cap-gpui"); + std::fs::create_dir_all(image.parent().unwrap()).unwrap(); + std::fs::copy("/bin/sleep", &image).unwrap(); + // A test forking on another thread while the copy was open for + // writing holds that descriptor until its exec, and exec fails + // with ETXTBSY until then. + let started = Instant::now(); + let child = loop { + match std::process::Command::new(&image).arg("60").spawn() { + Ok(child) => break child, + Err(error) + if error.kind() == std::io::ErrorKind::ExecutableFileBusy + && started.elapsed() < Duration::from_secs(5) => + { + std::thread::sleep(Duration::from_millis(10)); + } + Err(error) => panic!("could not start the fake Cap: {error}"), + } + }; + let fake = Self(child); + while !is_cap_gpui(fake.pid() as i32) { + assert!(started.elapsed() < Duration::from_secs(5)); + std::thread::sleep(Duration::from_millis(10)); + } + fake + } + + fn pid(&self) -> u32 { + self.0.id() + } + + fn running(&mut self) -> bool { + self.0.try_wait().unwrap().is_none() + } + } + + impl Drop for FakeCap { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } + + fn unanswered(_: u32) -> std::io::Result<()> { + Err(std::io::Error::new( + std::io::ErrorKind::TimedOut, + "no answer", + )) + } + + #[test] + fn an_instance_that_already_exited_starts_a_new_one_without_asking() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("cap-gpui.pid"); + let mut child = std::process::Command::new("true").spawn().unwrap(); + std::fs::write(&path, child.id().to_string()).unwrap(); + child.wait().unwrap(); + let launch = acquire_linux_instance(&path, unanswered, || panic!("asked")).unwrap(); + assert!(matches!(launch, LinuxLaunch::Start(_))); + } + + #[test] + fn a_responsive_instance_is_handed_off_without_asking() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("cap-gpui.pid"); + let mut running = FakeCap::start(directory.path(), "running"); + std::fs::write(&path, running.pid().to_string()).unwrap(); + let launch = acquire_linux_instance(&path, |_| Ok(()), || panic!("asked")).unwrap(); + assert!(matches!(launch, LinuxLaunch::HandedOff)); + assert!(running.running()); + } + + #[test] + fn a_cancelled_prompt_leaves_the_hung_instance_running() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("cap-gpui.pid"); + let mut hung = FakeCap::start(directory.path(), "hung"); + std::fs::write(&path, hung.pid().to_string()).unwrap(); + let launch = acquire_linux_instance(&path, unanswered, || false).unwrap(); + assert!(matches!(launch, LinuxLaunch::Cancelled)); + assert!(hung.running()); + } + + #[test] + fn a_confirmed_hung_instance_is_ended_and_this_launch_starts() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("cap-gpui.pid"); + let mut hung = FakeCap::start(directory.path(), "hung"); + std::fs::write(&path, hung.pid().to_string()).unwrap(); + let mut asked = 0; + let launch = acquire_linux_instance(&path, unanswered, || { + asked += 1; + true + }) + .unwrap(); + assert!(matches!(launch, LinuxLaunch::Start(_))); + assert_eq!(asked, 1); + assert!(!hung.running()); + } + + /// The user confirms after the copy has started answering again: it is + /// handed the launch instead of being ended. + #[test] + fn an_instance_that_recovers_during_the_prompt_is_kept() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("cap-gpui.pid"); + let mut recovered = FakeCap::start(directory.path(), "recovered"); + std::fs::write(&path, recovered.pid().to_string()).unwrap(); + let answers = std::cell::Cell::new(false); + let launch = acquire_linux_instance( + &path, + |pid| { + if answers.get() { + Ok(()) + } else { + unanswered(pid) + } + }, + || { + answers.set(true); + true + }, + ); + assert!(matches!(launch.unwrap(), LinuxLaunch::HandedOff)); + assert!(recovered.running()); + } + + /// Two launches meet the same hung copy. The second waits while the first + /// holds the prompt, then hands off to the copy the first one started + /// instead of starting a second one. + #[test] + fn a_second_launch_hands_off_to_the_copy_the_first_one_started() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("cap-gpui.pid"); + let mut hung = FakeCap::start(directory.path(), "hung"); + let replacement = FakeCap::start(directory.path(), "replacement"); + std::fs::write(&path, hung.pid().to_string()).unwrap(); + + let LinuxLaunch::Start(lock) = acquire_linux_instance(&path, unanswered, || true).unwrap() + else { + panic!("the first launch did not start"); + }; + assert!(!hung.running()); + + let (sender, receiver) = std::sync::mpsc::channel(); + let second = { + let path = path.clone(); + std::thread::spawn(move || { + let launch = acquire_linux_instance( + &path, + |pid| { + sender.send(pid).unwrap(); + Ok(()) + }, + || panic!("the second launch asked"), + ); + matches!(launch, Ok(LinuxLaunch::HandedOff)) + }) + }; + std::thread::sleep(Duration::from_millis(300)); + assert!(!second.is_finished()); + std::fs::write(&path, replacement.pid().to_string()).unwrap(); + drop(lock); + + assert!(second.join().unwrap()); + assert_eq!(receiver.recv().unwrap(), replacement.pid()); + } +} + +#[cfg(test)] +mod takeover_step_tests { + use super::*; + + #[test] + fn only_the_confirmed_process_is_ended_and_only_once() { + assert_eq!(takeover_step(7, None, None), TakeoverStep::Ask); + assert_eq!(takeover_step(7, Some(7), None), TakeoverStep::End); + assert_eq!(takeover_step(8, Some(7), None), TakeoverStep::Ask); + assert_eq!(takeover_step(7, Some(7), Some(7)), TakeoverStep::GiveUp); + assert_eq!(takeover_step(8, Some(8), Some(7)), TakeoverStep::End); + } +} diff --git a/apps/desktop-gpui/src/startup.rs b/apps/desktop-gpui/src/startup.rs new file mode 100644 index 00000000000..ae9ef4de58b --- /dev/null +++ b/apps/desktop-gpui/src/startup.rs @@ -0,0 +1,154 @@ +//! What a launch shows when it cannot become a working Cap. +//! +//! A release build on Windows has no console, so before this module every +//! early exit (an unresponsive running copy, a failed instance lock, a panic +//! while gpui starts, a main window that would not open) ended the process +//! with nothing on screen and, for the earliest ones, nothing in the log. + +use std::sync::{ + Mutex, OnceLock, PoisonError, + atomic::{AtomicBool, Ordering}, +}; + +use tracing_appender::non_blocking::WorkerGuard; + +use crate::i18n::tr; + +static MAIN_THREAD: OnceLock = OnceLock::new(); +static FINISHED: AtomicBool = AtomicBool::new(false); +static FAILURE_SHOWN: AtomicBool = AtomicBool::new(false); +static LOG_GUARD: Mutex> = Mutex::new(None); + +/// Call first thing in `main`, right after logging starts. The log writer's +/// guard lives here so an early exit can drain it: `process::exit` skips +/// destructors, and a launch that handed off to a running Cap used to lose +/// every line it had queued, including why it left. +pub fn begin(log_guard: Option) { + *LOG_GUARD.lock().unwrap_or_else(PoisonError::into_inner) = log_guard; + let _ = MAIN_THREAD.set(std::thread::current().id()); + tracing::info!( + version = env!("CARGO_PKG_VERSION"), + pid = std::process::id(), + executable = %std::env::current_exe() + .map(|path| path.display().to_string()) + .unwrap_or_default(), + "Cap starting" + ); +} + +/// Writes every queued log line to disk. +pub fn flush_log() { + drop( + LOG_GUARD + .lock() + .unwrap_or_else(PoisonError::into_inner) + .take(), + ); +} + +/// `process::exit` after the log is on disk. +pub fn exit(code: i32) -> ! { + flush_log(); + std::process::exit(code); +} + +/// The main window is open; from here a panic is the crash reporter's job. +pub fn finished() { + FINISHED.store(true, Ordering::Release); +} + +fn on_main_thread() -> bool { + MAIN_THREAD + .get() + .is_some_and(|main| *main == std::thread::current().id()) +} + +/// Called by the panic hook. Only a main-thread panic before the main window +/// opens ends the launch, and only the main thread may show a dialog on macOS. +pub fn report_panic(message: &str, location: &str) { + if FINISHED.load(Ordering::Acquire) || !on_main_thread() { + return; + } + show_failure(&format!("{message} ({location})")); +} + +/// Shows why Cap could not start, then exits. +pub fn fail(error: impl std::fmt::Display) -> ! { + let error = error.to_string(); + tracing::error!(%error, "Cap could not start"); + crate::crash_capture::record_startup_failure(&error); + show_failure(&error); + exit(1); +} + +fn show_failure(error: &str) { + if FAILURE_SHOWN.swap(true, Ordering::AcqRel) { + return; + } + load_language(); + let folder = crate::diagnostics::logs_dir(); + show_error( + tr::dialog::startup::failed_title(), + &tr::dialog::startup::failed(error, folder.display()), + ); +} + +/// Asks whether to end a running copy that did not answer the reopen request. +pub fn confirm_quit_unresponsive() -> bool { + load_language(); + prepare_dialog(); + crate::platform::confirm_dialog( + tr::dialog::startup::unresponsive_title(), + tr::dialog::startup::unresponsive(), + tr::dialog::startup::quit_and_reopen(), + tr::common::cancel(), + true, + ) +} + +fn load_language() { + crate::i18n::init(crate::store::GeneralSettings::load().ui_language.as_deref()); +} + +#[cfg(target_os = "windows")] +fn show_error(title: &str, message: &str) { + use windows_sys::Win32::UI::WindowsAndMessaging::{ + MB_ICONERROR, MB_OK, MB_SETFOREGROUND, MB_TOPMOST, MessageBoxW, + }; + + let wide = |text: &str| { + text.encode_utf16() + .chain(std::iter::once(0)) + .collect::>() + }; + let (title, message) = (wide(title), wide(message)); + unsafe { + MessageBoxW( + std::ptr::null_mut(), + message.as_ptr(), + title.as_ptr(), + MB_OK | MB_ICONERROR | MB_SETFOREGROUND | MB_TOPMOST, + ); + } +} + +#[cfg(not(target_os = "windows"))] +fn show_error(title: &str, message: &str) { + if !on_main_thread() { + return; + } + prepare_dialog(); + crate::platform::alert_dialog(title, message); +} + +/// `NSAlert` does nothing until `NSApp` exists, and a startup failure can come +/// before gpui creates it. +#[cfg(target_os = "macos")] +fn prepare_dialog() { + if on_main_thread() { + crate::platform::activate_app(); + } +} + +#[cfg(not(target_os = "macos"))] +fn prepare_dialog() {} diff --git a/apps/desktop-gpui/src/store.rs b/apps/desktop-gpui/src/store.rs index 51c3ad37b54..17253481f5c 100644 --- a/apps/desktop-gpui/src/store.rs +++ b/apps/desktop-gpui/src/store.rs @@ -534,6 +534,52 @@ fn update_store(mutate: impl FnOnce(&mut Map) -> bool) -> bool { written } +/// A store that reads but does not parse as a JSON object (zero-filled after a +/// power loss, truncated by a crash) refuses every write, so onboarding could +/// never save its progress and stayed on "Could not save onboarding progress" +/// forever. While it does not parse, its onboarding flags, auth and presets are +/// already invisible to Cap, so its bytes are kept beside it and the progress +/// is saved to a fresh store. A store that could not be read at all is left +/// alone. +fn set_aside_unparseable_store(path: &Path) -> bool { + let _guard = STORE_UPDATE_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let Ok(bytes) = std::fs::read(path) else { + return false; + }; + if bytes.iter().all(u8::is_ascii_whitespace) { + return false; + } + if matches!( + serde_json::from_slice::(&bytes), + Ok(Value::Object(_)) + ) { + return false; + } + let stamp = SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .map(|elapsed| elapsed.as_millis()) + .unwrap_or_default(); + let mut name = path.file_name().unwrap_or_default().to_os_string(); + name.push(format!(".unreadable-{stamp}")); + let kept = path.with_file_name(name); + match std::fs::rename(path, &kept) { + Ok(()) => { + store_cache().remove(path); + tracing::error!( + kept = %kept.display(), + "the settings store did not parse; kept it aside and started a new one" + ); + true + } + Err(error) => { + tracing::error!(%error, "could not set aside the unparseable settings store"); + false + } + } +} + /// Pretty JSON, two-space indent, no trailing newline -- byte-shape identical /// to what tauri-plugin-store writes, so a store the two apps take turns on /// does not churn. @@ -1334,7 +1380,13 @@ pub fn has_completed_startup() -> bool { } pub fn set_has_completed_startup(value: bool) -> bool { - set_store_setting(GENERAL_SETTINGS, "hasCompletedStartup", Value::Bool(value)) + set_onboarding_progress("hasCompletedStartup", value) +} + +fn set_onboarding_progress(key: &str, value: bool) -> bool { + set_store_setting(GENERAL_SETTINGS, key, Value::Bool(value)) + || (set_aside_unparseable_store(&tauri_store_path()) + && set_store_setting(GENERAL_SETTINGS, key, Value::Bool(value))) } pub fn has_completed_onboarding() -> bool { @@ -1345,11 +1397,7 @@ pub fn has_completed_onboarding() -> bool { } pub fn set_has_completed_onboarding(value: bool) -> bool { - set_store_setting( - GENERAL_SETTINGS, - "hasCompletedOnboarding", - Value::Bool(value), - ) + set_onboarding_progress("hasCompletedOnboarding", value) } /// `should_show_onboarding` (`lib.rs:463-477`): first-run flags or missing @@ -2308,7 +2356,11 @@ mod tests { std::fs::write(&store.path, "{ not json").unwrap(); backdate(&store.path, seconds_ago(30)); assert!(!has_completed_startup()); - assert!(!set_has_completed_onboarding(true)); + assert!(!set_store_setting( + GENERAL_SETTINGS, + "hideDockIcon", + Value::Bool(true) + )); std::fs::remove_file(&store.path).unwrap(); assert!(!has_completed_startup()); assert!(store_section(GENERAL_SETTINGS).is_empty()); @@ -3068,6 +3120,67 @@ mod tests { } } + /// A zero-filled store (NTFS after a power loss) or one cut off mid-object + /// blocked onboarding forever. Onboarding sets the unreadable bytes aside + /// and saves its progress; every other writer still refuses. + #[test] + fn onboarding_progress_sets_aside_an_unparseable_store() { + for contents in [ + "\0\0\0\0\0\0\0\0", + "{ this is not json", + r#"{"auth":"token""#, + "null", + "[]", + ] { + let store = TempStore::new("unparseable-onboarding", Some(contents)); + assert!(!set_store_setting( + GENERAL_SETTINGS, + "hideDockIcon", + Value::Bool(true) + )); + assert_eq!(std::fs::read_to_string(&store.path).unwrap(), contents); + assert!(!has_completed_startup()); + + assert!(set_has_completed_startup(true)); + assert!(set_has_completed_onboarding(true)); + assert!(has_completed_startup()); + assert!(has_completed_onboarding()); + assert_eq!( + store.read(), + serde_json::json!({ + "general_settings": { + "hasCompletedStartup": true, + "hasCompletedOnboarding": true + } + }) + ); + + let directory = store.path.parent().unwrap(); + let prefix = format!( + "{}.unreadable-", + store.path.file_name().unwrap().to_string_lossy() + ); + let kept = std::fs::read_dir(directory) + .unwrap() + .filter_map(Result::ok) + .filter(|entry| entry.file_name().to_string_lossy().starts_with(&prefix)) + .map(|entry| entry.path()) + .collect::>(); + assert_eq!(kept.len(), 1, "{kept:?}"); + assert_eq!(std::fs::read_to_string(&kept[0]).unwrap(), contents); + std::fs::remove_file(&kept[0]).unwrap(); + } + } + + #[test] + fn onboarding_progress_leaves_an_unreadable_store_alone() { + let store = TempStore::new("unreadable-onboarding", None); + std::fs::create_dir_all(&store.path).unwrap(); + assert!(!set_has_completed_startup(true)); + assert!(store.path.is_dir()); + std::fs::remove_dir(&store.path).unwrap(); + } + #[test] fn onboarding_progress_recovers_an_empty_store() { for contents in ["", " \t\r\n"] { diff --git a/scripts/bundle-gpui.mjs b/scripts/bundle-gpui.mjs index e73b6556029..4852b964802 100644 --- a/scripts/bundle-gpui.mjs +++ b/scripts/bundle-gpui.mjs @@ -59,6 +59,7 @@ export function gpuiPlatformConfig(platform) { "../../target/native-deps/dxc/*.dll": "./", "../../target/native-deps/dxc/LICENSE-*.txt": "licenses/dxc/", "../../target/native-deps/onnxruntime/lib/*.dll": "./", + "../../target/native-deps/vcruntime/*.dll": "./", }, }, }; diff --git a/scripts/bundle-gpui.test.mjs b/scripts/bundle-gpui.test.mjs index 2376b67f305..c1c0c20f4cb 100644 --- a/scripts/bundle-gpui.test.mjs +++ b/scripts/bundle-gpui.test.mjs @@ -162,9 +162,56 @@ test("platform resources point at the shared native dependencies", () => { const windows = gpuiPlatformConfig("win32").bundle.resources; assert.equal(windows["../../target/ffmpeg/bin/*.dll"], "./"); assert.equal(windows["../../target/native-deps/onnxruntime/lib/*.dll"], "./"); + assert.equal(windows["../../target/native-deps/vcruntime/*.dll"], "./"); assert.equal(gpuiPlatformConfig("linux"), null); }); +test("the Windows installer copies nothing while a CLI from this install runs", () => { + const hooks = readFileSync( + path.join(gpuiDirectory, gpuiConfig.bundle.windows.nsis.installerHooks), + "utf8", + ); + const macro = (name) => + hooks.match( + new RegExp(`!macro ${name}(?: [A-Z_]+)?\\r?\\n([\\s\\S]*?)!macroend`), + )?.[1] ?? ""; + for (const hook of ["NSIS_HOOK_PREINSTALL", "NSIS_HOOK_PREUNINSTALL"]) { + const body = macro(hook); + assert.match(body, /!insertmacro WaitForCapCommandLineTools "/, hook); + assert.ok( + body.indexOf("EndCapMcpServers") < + body.indexOf("WaitForCapCommandLineTools"), + hook, + ); + } + const wait = macro("WaitForCapCommandLineTools"); + assert.match( + wait, + /\$\$_\.Name -eq 'cap-cli\.exe' -or \$\$_\.Name -eq 'cap-muxer\.exe'/, + ); + assert.match(wait, /GetDirectoryName\(\$\$_\.ExecutablePath\) -eq \$\$dir/); + assert.match(wait, /exit 2 \} catch \{ exit 0 \}/); + assert.match(wait, /\$\{If\} \$0 == 2/); + const probe = wait.indexOf('FindProcessCurrentUser "cap-cli.exe"'); + assert.ok(probe >= 0 && probe < wait.indexOf("nsExec::ExecToStack")); + assert.match(wait, /FindProcessCurrentUser "cap-muxer\.exe"/); + assert.match( + wait, + /MB_RETRYCANCEL[^\n]*\/SD IDCANCEL IDRETRY \$\{CapToolsCheck\}/, + ); + assert.match(wait, /Abort "\$\{ABORT_TEXT\}"/); + const lines = wait + .split(/\r?\n/) + .map((line) => line.trim()) + .filter(Boolean); + assert.deepEqual(lines.slice(1, 3), ["Push $0", "Push $1"]); + assert.deepEqual(lines.slice(-3), [ + "Pop $1", + "Pop $0", + "!undef CapToolsCheck", + ]); +}); + test("tauri bundle runs against the GPUI crate with its pinned toolchain", () => { assert.deepEqual(bundleArguments("x86_64-unknown-linux-gnu", ["--verbose"]), [ "tauri", diff --git a/scripts/setup.js b/scripts/setup.js index a086340d72e..549faffadc4 100644 --- a/scripts/setup.js +++ b/scripts/setup.js @@ -232,6 +232,8 @@ async function main() { "/", )}"\n`; + await setupWindowsVcRuntime(vcInstallDir.trim()); + const cmakePath = path.join( vcInstallDir.trim(), "Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/bin/cmake.exe", @@ -583,6 +585,58 @@ async function setupLinuxOnnxRuntime() { return outputPath; } +const WINDOWS_VC_RUNTIME_DLLS = [ + "msvcp140.dll", + "msvcp140_1.dll", + "vcruntime140.dll", + "vcruntime140_1.dll", +]; + +// Cap.exe, cap-cli.exe, cap-muxer.exe, onnxruntime.dll and dxcompiler.dll all +// import the Visual C++ runtime, which a clean Windows 11 does not have. The +// installer ships the runtime next to them (app-local deployment) from the +// same Visual Studio that linked them, so it is never older than the build. +async function setupWindowsVcRuntime(vcInstallDir) { + const redistArch = { x86_64: "x64", aarch64: "arm64" }[arch]; + if (!redistArch) + throw new Error( + `Unsupported Windows architecture for the VC runtime: ${arch}`, + ); + const version = ( + await fs.readFile( + path.join( + vcInstallDir, + "VC/Auxiliary/Build/Microsoft.VCRedistVersion.default.txt", + ), + "utf-8", + ) + ).trim(); + const archDir = path.join( + vcInstallDir, + "VC/Redist/MSVC", + version, + redistArch, + ); + const crtDir = (await fs.readdir(archDir)) + .filter((name) => /^Microsoft\.VC\d+\.CRT$/.test(name)) + .sort() + .pop(); + if (!crtDir) + throw new Error( + `No Visual C++ runtime redistributable found in ${archDir}`, + ); + + const outputDir = path.join(targetDir, "native-deps", "vcruntime"); + await fs.rm(outputDir, { recursive: true, force: true }); + await fs.mkdir(outputDir, { recursive: true }); + for (const name of WINDOWS_VC_RUNTIME_DLLS) + await fs.copyFile( + path.join(archDir, crtDir, name), + path.join(outputDir, name), + ); + console.log(`Prepared the Visual C++ runtime ${version} for ${redistArch}`); +} + async function setupWindowsDxc() { const asset = { version: "1.9.2607.13",