From 99c524506b83671ff578566add7c6b192ff82817 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sat, 14 Nov 2026 00:45:39 -0500 Subject: [PATCH 01/13] fix(desktop-gpui): ship the Visual C++ runtime in the Windows installer --- .github/workflows/desktop-release.yml | 3 +- scripts/bundle-gpui.mjs | 1 + scripts/setup.js | 54 +++++++++++++++++++++++++++ 3 files changed, 57 insertions(+), 1 deletion(-) 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/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/setup.js b/scripts/setup.js index ec82f6cd376..25cdf577545 100644 --- a/scripts/setup.js +++ b/scripts/setup.js @@ -235,6 +235,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", From 7cd5cbbcccbca7919f1a4b01fb502e967c4e36aa Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sat, 14 Nov 2026 00:45:40 -0500 Subject: [PATCH 02/13] fix(desktop-gpui): stop the Windows installer replacing files while the CLI runs --- .../packaging/windows/installer-hooks.nsh | 28 ++++++++++++ scripts/bundle-gpui.test.mjs | 44 +++++++++++++++++++ 2 files changed, 72 insertions(+) diff --git a/apps/desktop-gpui/packaging/windows/installer-hooks.nsh b/apps/desktop-gpui/packaging/windows/installer-hooks.nsh index f696c1c5ffe..e596de2b76d 100644 --- a/apps/desktop-gpui/packaging/windows/installer-hooks.nsh +++ b/apps/desktop-gpui/packaging/windows/installer-hooks.nsh @@ -18,12 +18,39 @@ 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. +; Exit code 2 means one 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}: + 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} + 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 +61,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/scripts/bundle-gpui.test.mjs b/scripts/bundle-gpui.test.mjs index 2376b67f305..7b3c4732a3b 100644 --- a/scripts/bundle-gpui.test.mjs +++ b/scripts/bundle-gpui.test.mjs @@ -162,9 +162,53 @@ 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/); + 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", From 2d18189159ef5ec89d7a2865189b22e617115b4a Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sat, 14 Nov 2026 00:45:40 -0500 Subject: [PATCH 03/13] fix(desktop-gpui): let onboarding recover from an unparseable settings store --- apps/desktop-gpui/src/store.rs | 127 +++++++++++++++++++++++++++++++-- 1 file changed, 120 insertions(+), 7 deletions(-) diff --git a/apps/desktop-gpui/src/store.rs b/apps/desktop-gpui/src/store.rs index d305d42db02..b334860ed45 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 @@ -2304,7 +2352,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()); @@ -3064,6 +3116,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"] { From 79927bd25186902aea53725c46adc5054f30793c Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sat, 14 Nov 2026 00:45:40 -0500 Subject: [PATCH 04/13] fix(desktop-gpui): never exit silently when Cap cannot start or a running copy hangs --- apps/desktop-gpui/Cargo.toml | 2 + apps/desktop-gpui/locales/de.toml | 7 + apps/desktop-gpui/locales/en.toml | 7 + apps/desktop-gpui/locales/es.toml | 7 + apps/desktop-gpui/locales/fr.toml | 7 + apps/desktop-gpui/locales/hi.toml | 7 + apps/desktop-gpui/locales/ja.toml | 7 + apps/desktop-gpui/locales/zh-CN.toml | 7 + apps/desktop-gpui/src/crash_capture.rs | 7 + apps/desktop-gpui/src/main.rs | 11 +- apps/desktop-gpui/src/single_instance.rs | 526 ++++++++++++++++++++--- apps/desktop-gpui/src/startup.rs | 131 ++++++ 12 files changed, 659 insertions(+), 67 deletions(-) create mode 100644 apps/desktop-gpui/src/startup.rs diff --git a/apps/desktop-gpui/Cargo.toml b/apps/desktop-gpui/Cargo.toml index a39d6dc923a..8ef6eaf6abc 100644 --- a/apps/desktop-gpui/Cargo.toml +++ b/apps/desktop-gpui/Cargo.toml @@ -215,10 +215,12 @@ windows-sys = { version = "0.59", features = [ "Win32_Storage_FileSystem", "Win32_System_Console", "Win32_System_Diagnostics_Debug", + "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Registry", + "Win32_System_RemoteDesktop", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_UI_Shell", diff --git a/apps/desktop-gpui/locales/de.toml b/apps/desktop-gpui/locales/de.toml index c96d36f22a2..fda5f681690 100644 --- a/apps/desktop-gpui/locales/de.toml +++ b/apps/desktop-gpui/locales/de.toml @@ -3204,6 +3204,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 29f268aa5c6..deeb5134d72 100644 --- a/apps/desktop-gpui/locales/en.toml +++ b/apps/desktop-gpui/locales/en.toml @@ -3206,6 +3206,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 27fbf306d17..e37806f2c6a 100644 --- a/apps/desktop-gpui/locales/es.toml +++ b/apps/desktop-gpui/locales/es.toml @@ -3204,6 +3204,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 87b46c59460..8b202e0ca57 100644 --- a/apps/desktop-gpui/locales/fr.toml +++ b/apps/desktop-gpui/locales/fr.toml @@ -3204,6 +3204,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 319ed6675bb..bd749c39165 100644 --- a/apps/desktop-gpui/locales/hi.toml +++ b/apps/desktop-gpui/locales/hi.toml @@ -3204,6 +3204,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 d007debfd05..16197862cd4 100644 --- a/apps/desktop-gpui/locales/ja.toml +++ b/apps/desktop-gpui/locales/ja.toml @@ -3204,6 +3204,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 922d4ee4a5d..a748b22be14 100644 --- a/apps/desktop-gpui/locales/zh-CN.toml +++ b/apps/desktop-gpui/locales/zh-CN.toml @@ -3204,6 +3204,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/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/main.rs b/apps/desktop-gpui/src/main.rs index acdd53da302..925148fa28f 100644 --- a/apps/desktop-gpui/src/main.rs +++ b/apps/desktop-gpui/src/main.rs @@ -99,6 +99,7 @@ mod sign_in; mod single_instance; #[cfg(debug_assertions)] mod snapshot; +mod startup; mod store; mod target_overlay; mod target_thumbnails; @@ -337,6 +338,7 @@ fn main() { } let _log_guard = init_logging(); + startup::begin(); crash_capture::install(&diagnostics::logs_dir()); #[cfg(target_os = "linux")] if let Some(wayland_display) = stale_wayland_display { @@ -477,11 +479,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(); diff --git a/apps/desktop-gpui/src/single_instance.rs b/apps/desktop-gpui/src/single_instance.rs index f08ded5b676..8276d2ee9f2 100644 --- a/apps/desktop-gpui/src/single_instance.rs +++ b/apps/desktop-gpui/src/single_instance.rs @@ -44,17 +44,16 @@ pub fn acquire() { Ok(Some(lock)) => lock, Ok(None) => std::process::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)] @@ -67,14 +66,15 @@ pub fn acquire() { && 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" - ), + Ok(()) => { + tracing::info!(pid, "Requested the existing Cap GPUI controls"); + std::process::exit(0); + } + Err(error) => { + tracing::warn!(pid, %error, "The running Cap GPUI did not answer the reopen request"); + take_over_from_unresponsive_linux_instance(pid); + } } - std::process::exit(0); } #[cfg(not(target_os = "macos"))] { @@ -88,15 +88,55 @@ 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}")); + } +} + +/// An instance that exited between the pidfile read and the reopen is simply +/// gone. One that is still alive and did not answer is hung, and the user +/// decides whether to end it; exiting quietly left them with no Cap at all. +#[cfg(target_os = "linux")] +fn take_over_from_unresponsive_linux_instance(pid: i32) { + if !is_cap_gpui(pid) { + tracing::info!(pid, "the previous Cap GPUI exited; starting a new one"); + return; + } + if !crate::startup::confirm_quit_unresponsive() { + std::process::exit(0); + } + if !end_linux_instance(pid, || is_cap_gpui(pid)) { + crate::startup::fail(format!( + "The copy of Cap that isn't responding (process {pid}) could not be quit." + )); } + tracing::info!(pid, "ended the unresponsive Cap GPUI"); +} + +#[cfg(target_os = "linux")] +fn end_linux_instance(pid: i32, alive: impl Fn() -> bool) -> bool { + let exited_within = |limit: std::time::Duration| { + let started = std::time::Instant::now(); + loop { + if !alive() { + return true; + } + if started.elapsed() >= limit { + return false; + } + std::thread::sleep(std::time::Duration::from_millis(50)); + } + }; + unsafe { libc::kill(pid, libc::SIGTERM) }; + if exited_within(std::time::Duration::from_secs(3)) { + return true; + } + unsafe { libc::kill(pid, libc::SIGKILL) }; + exited_within(std::time::Duration::from_secs(3)) } /// Linux zombies retain their comm name but lose their exe link. @@ -1046,48 +1086,184 @@ fn acquire_windows_instance(path: &Path) { .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 ended_unresponsive = false; + 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 unresponsive = match handed_off { + Ok(()) => std::process::exit(0), + Err(pid) => pid, + }; + if ended_unresponsive { + crate::startup::fail( + "Another copy of Cap is still running and could not be quit. Restart your computer, then open Cap again.", + ); + } + tracing::warn!( + pid = ?unresponsive, + "the running Cap GPUI did not answer the reopen request" + ); + if !crate::startup::confirm_quit_unresponsive() { + std::process::exit(0); + } + let pids = match unresponsive { + Some(pid) => vec![pid], + None => other_windows_instances(), + }; + for pid in pids { + 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") } - break; } - std::thread::sleep(std::time::Duration::from_millis(50)); } - - let _ = unsafe { CloseHandle(mutex) }; - std::process::exit(0); - } + ended_unresponsive = true; + }; 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}")); } } +/// `Err` carries the running instance's pid when one was identified. A +/// responsive instance acknowledges a reopen from its listener thread within +/// milliseconds, so a failed reopen means its process is stuck; activating +/// its window then showed nothing and the new launch exited without a trace. +/// A window that still answers messages (a build without the reopen +/// endpoint) is activated as before. +#[cfg(windows)] +fn hand_off_to_windows_instance(path: &Path) -> Result<(), Option> { + 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); + return Ok(()); + } + return match reopen_windows_instance(path, pid) { + Ok(()) => Ok(()), + Err(error) => { + tracing::warn!(%error, "could not reopen the running Cap GPUI"); + match windows_instance_window(pid) { + Some(window) if windows_window_responds(window) => { + activate_windows_window(window); + Ok(()) + } + _ => Err(Some(pid)), + } + } + }; + } + std::thread::sleep(std::time::Duration::from_millis(50)); + } + Err(None) +} + +#[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, 2000, &mut result) != 0 } +} + +/// Every other Cap process in this logon session: the mutex is per session, +/// and an instance whose pidfile was lost still holds it. +#[cfg(windows)] +fn other_windows_instances() -> Vec { + use windows_sys::Win32::{ + Foundation::{CloseHandle, INVALID_HANDLE_VALUE}, + System::{ + Diagnostics::ToolHelp::{ + CreateToolhelp32Snapshot, PROCESSENTRY32W, Process32FirstW, Process32NextW, + TH32CS_SNAPPROCESS, + }, + RemoteDesktop::ProcessIdToSessionId, + }, + }; + + let own_pid = std::process::id(); + let mut own_session = 0; + if unsafe { ProcessIdToSessionId(own_pid, &mut own_session) } == 0 { + return Vec::new(); + } + let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) }; + if snapshot == INVALID_HANDLE_VALUE { + return Vec::new(); + } + let mut pids = Vec::new(); + let mut entry = PROCESSENTRY32W { + dwSize: std::mem::size_of::() as u32, + ..unsafe { std::mem::zeroed() } + }; + let mut more = unsafe { Process32FirstW(snapshot, &mut entry) } != 0; + while more { + let pid = entry.th32ProcessID; + let mut session = 0; + if pid != own_pid + && unsafe { ProcessIdToSessionId(pid, &mut session) } != 0 + && session == own_session + && windows_process_is_cap(pid) + { + pids.push(pid); + } + more = unsafe { Process32NextW(snapshot, &mut entry) } != 0; + } + let _ = unsafe { CloseHandle(snapshot) }; + pids +} + +#[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, + }, + }; + + if !windows_process_is_cap(pid) { + return Ok(()); + } + let process = unsafe { OpenProcess(PROCESS_TERMINATE | PROCESS_SYNCHRONIZE, 0, pid) }; + if process.is_null() { + return Err(std::io::Error::last_os_error()); + } + 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; @@ -1330,6 +1506,12 @@ fn read_forwarded_request( #[cfg(windows)] fn windows_instance_pid(path: &Path) -> Option { + let pid = std::fs::read_to_string(path).ok()?.trim().parse().ok()?; + windows_process_is_cap(pid).then_some(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 +1520,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 +1530,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 +1595,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)] @@ -2990,3 +3180,215 @@ 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 ending_an_unresponsive_instance_waits_for_it_to_exit() { + let mut fake = FakeCap::start(); + assert!(windows_process_is_cap(fake.pid())); + assert!(other_windows_instances().contains(&fake.pid())); + assert!(!other_windows_instances().contains(&std::process::id())); + end_windows_process(fake.pid()).unwrap(); + assert!(exited(&mut fake.child)); + assert!(!windows_process_is_cap(fake.pid())); + } + + #[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(); + assert!(!other_windows_instances().contains(&other.id())); + 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}; + + fn alive(child: &std::sync::Mutex) -> bool { + child.lock().unwrap().try_wait().unwrap().is_none() + } + + #[test] + fn a_hung_instance_is_ended_with_sigterm() { + let child = std::sync::Mutex::new( + std::process::Command::new("sleep") + .arg("60") + .spawn() + .unwrap(), + ); + let pid = child.lock().unwrap().id() as i32; + let started = Instant::now(); + assert!(end_linux_instance(pid, || alive(&child))); + assert!(started.elapsed() < Duration::from_secs(3)); + } + + #[test] + fn an_instance_that_ignores_sigterm_is_killed() { + let child = std::sync::Mutex::new( + std::process::Command::new("sh") + .args(["-c", "trap '' TERM; while :; do sleep 1; done"]) + .spawn() + .unwrap(), + ); + let pid = child.lock().unwrap().id() as i32; + std::thread::sleep(Duration::from_millis(200)); + let started = Instant::now(); + assert!(end_linux_instance(pid, || alive(&child))); + assert!(started.elapsed() >= Duration::from_secs(3)); + assert!(started.elapsed() < Duration::from_secs(6)); + } + + #[test] + fn an_instance_that_already_exited_starts_a_new_one_without_asking() { + let mut child = std::process::Command::new("true").spawn().unwrap(); + let pid = child.id() as i32; + child.wait().unwrap(); + take_over_from_unresponsive_linux_instance(pid); + } +} diff --git a/apps/desktop-gpui/src/startup.rs b/apps/desktop-gpui/src/startup.rs new file mode 100644 index 00000000000..7c41706b94a --- /dev/null +++ b/apps/desktop-gpui/src/startup.rs @@ -0,0 +1,131 @@ +//! 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::{ + OnceLock, + atomic::{AtomicBool, Ordering}, +}; + +use crate::i18n::tr; + +static MAIN_THREAD: OnceLock = OnceLock::new(); +static FINISHED: AtomicBool = AtomicBool::new(false); +static FAILURE_SHOWN: AtomicBool = AtomicBool::new(false); + +/// Call first thing in `main`, after logging starts. +pub fn begin() { + 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" + ); +} + +/// 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); + std::process::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() {} From e8995f872bccf5fb553779d0d93a168dc3d4943a Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sat, 14 Nov 2026 00:49:16 -0500 Subject: [PATCH 05/13] fix(desktop-gpui): activate a responsive Cap instead of offering to quit it --- apps/desktop-gpui/src/single_instance.rs | 53 ++++++++++++++---------- 1 file changed, 31 insertions(+), 22 deletions(-) diff --git a/apps/desktop-gpui/src/single_instance.rs b/apps/desktop-gpui/src/single_instance.rs index 8276d2ee9f2..735bb2283ca 100644 --- a/apps/desktop-gpui/src/single_instance.rs +++ b/apps/desktop-gpui/src/single_instance.rs @@ -1147,34 +1147,43 @@ fn acquire_windows_instance(path: &Path) { /// responsive instance acknowledges a reopen from its listener thread within /// milliseconds, so a failed reopen means its process is stuck; activating /// its window then showed nothing and the new launch exited without a trace. -/// A window that still answers messages (a build without the reopen -/// endpoint) is activated as before. +/// A Cap whose window still answers messages (a build without the reopen +/// endpoint, or one whose pidfile could not be written) is activated as +/// before, so a working instance is never offered for quitting. #[cfg(windows)] fn hand_off_to_windows_instance(path: &Path) -> Result<(), Option> { + let mut identified = None; 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); - return Ok(()); - } - return match reopen_windows_instance(path, pid) { - Ok(()) => Ok(()), - Err(error) => { - tracing::warn!(%error, "could not reopen the running Cap GPUI"); - match windows_instance_window(pid) { - Some(window) if windows_window_responds(window) => { - activate_windows_window(window); - Ok(()) - } - _ => Err(Some(pid)), - } - } - }; + identified = windows_instance_pid(path); + if identified.is_some() { + break; } std::thread::sleep(std::time::Duration::from_millis(50)); } - Err(None) + if let Some(pid) = identified { + tracing::info!(pid, "Cap GPUI is already running; bringing it forward"); + if forward_windows_deep_links(path, pid) { + activate_windows_instance(pid); + return Ok(()); + } + match reopen_windows_instance(path, pid) { + Ok(()) => return Ok(()), + Err(error) => tracing::warn!(%error, "could not reopen the running Cap GPUI"), + } + } + let candidates = match identified { + Some(pid) => vec![pid], + None => other_windows_instances(), + }; + for pid in candidates { + if let Some(window) = windows_instance_window(pid) + && windows_window_responds(window) + { + activate_windows_window(window); + return Ok(()); + } + } + Err(identified) } #[cfg(windows)] From f12f4a0db7998a03b486c82924362a10f2f919f9 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sat, 14 Nov 2026 01:16:34 -0500 Subject: [PATCH 06/13] test(desktop-gpui): cover the startup dialog strings in the dialog surface test --- .../src/i18n/dialogs_surface_tests.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) 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); From 9dc43d41ca0a2039595d97bc5653067f6297695d Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sat, 14 Nov 2026 01:47:34 -0500 Subject: [PATCH 07/13] fix(desktop-gpui): flush the log before an early launch exit --- apps/desktop-gpui/src/main.rs | 4 +-- apps/desktop-gpui/src/single_instance.rs | 10 +++---- apps/desktop-gpui/src/startup.rs | 33 ++++++++++++++++++++---- 3 files changed, 35 insertions(+), 12 deletions(-) diff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rs index 925148fa28f..58392d79416 100644 --- a/apps/desktop-gpui/src/main.rs +++ b/apps/desktop-gpui/src/main.rs @@ -337,8 +337,7 @@ fn main() { std::process::exit(status); } - let _log_guard = init_logging(); - startup::begin(); + startup::begin(init_logging()); crash_capture::install(&diagnostics::logs_dir()); #[cfg(target_os = "linux")] if let Some(wayland_display) = stale_wayland_display { @@ -844,6 +843,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 735bb2283ca..4d8192d9d2d 100644 --- a/apps/desktop-gpui/src/single_instance.rs +++ b/apps/desktop-gpui/src/single_instance.rs @@ -42,7 +42,7 @@ pub fn acquire() { activate_macos_instance, ) { Ok(Some(lock)) => lock, - Ok(None) => std::process::exit(0), + Ok(None) => crate::startup::exit(0), Err(error) => { crate::startup::fail(format!("Could not acquire the Cap instance lock: {error}")) } @@ -68,7 +68,7 @@ pub fn acquire() { match forward_linux_reopen(&path, pid as u32) { Ok(()) => { tracing::info!(pid, "Requested the existing Cap GPUI controls"); - std::process::exit(0); + crate::startup::exit(0); } Err(error) => { tracing::warn!(pid, %error, "The running Cap GPUI did not answer the reopen request"); @@ -107,7 +107,7 @@ fn take_over_from_unresponsive_linux_instance(pid: i32) { return; } if !crate::startup::confirm_quit_unresponsive() { - std::process::exit(0); + crate::startup::exit(0); } if !end_linux_instance(pid, || is_cap_gpui(pid)) { crate::startup::fail(format!( @@ -1103,7 +1103,7 @@ fn acquire_windows_instance(path: &Path) { let handed_off = hand_off_to_windows_instance(path); let _ = unsafe { CloseHandle(mutex) }; let unresponsive = match handed_off { - Ok(()) => std::process::exit(0), + Ok(()) => crate::startup::exit(0), Err(pid) => pid, }; if ended_unresponsive { @@ -1116,7 +1116,7 @@ fn acquire_windows_instance(path: &Path) { "the running Cap GPUI did not answer the reopen request" ); if !crate::startup::confirm_quit_unresponsive() { - std::process::exit(0); + crate::startup::exit(0); } let pids = match unresponsive { Some(pid) => vec![pid], diff --git a/apps/desktop-gpui/src/startup.rs b/apps/desktop-gpui/src/startup.rs index 7c41706b94a..ae9ef4de58b 100644 --- a/apps/desktop-gpui/src/startup.rs +++ b/apps/desktop-gpui/src/startup.rs @@ -6,18 +6,25 @@ //! with nothing on screen and, for the earliest ones, nothing in the log. use std::sync::{ - OnceLock, + 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); - -/// Call first thing in `main`, after logging starts. -pub fn begin() { +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"), @@ -29,6 +36,22 @@ pub fn begin() { ); } +/// 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); @@ -55,7 +78,7 @@ pub fn fail(error: impl std::fmt::Display) -> ! { tracing::error!(%error, "Cap could not start"); crate::crash_capture::record_startup_failure(&error); show_failure(&error); - std::process::exit(1); + exit(1); } fn show_failure(error: &str) { From e3e7f43ca55493e401c968e77b4d2b320bd2c9b9 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sat, 14 Nov 2026 02:07:25 -0500 Subject: [PATCH 08/13] perf(desktop-gpui): skip the installer's CLI check when no CLI process runs --- .../packaging/windows/installer-hooks.nsh | 23 +++++++++++++------ scripts/bundle-gpui.test.mjs | 3 +++ 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/apps/desktop-gpui/packaging/windows/installer-hooks.nsh b/apps/desktop-gpui/packaging/windows/installer-hooks.nsh index e596de2b76d..06c93ec885d 100644 --- a/apps/desktop-gpui/packaging/windows/installer-hooks.nsh +++ b/apps/desktop-gpui/packaging/windows/installer-hooks.nsh @@ -24,20 +24,29 @@ SetCompressorDictSize 128 ; 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. -; Exit code 2 means one is still running; any other failure of the check keeps -; the previous behaviour of going ahead. +; 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}: - 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 }"` + nsis_tauri_utils::FindProcessCurrentUser "cap-cli.exe" 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}" + ${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 diff --git a/scripts/bundle-gpui.test.mjs b/scripts/bundle-gpui.test.mjs index 7b3c4732a3b..c1c0c20f4cb 100644 --- a/scripts/bundle-gpui.test.mjs +++ b/scripts/bundle-gpui.test.mjs @@ -192,6 +192,9 @@ test("the Windows installer copies nothing while a CLI from this install runs", 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\}/, From 7bbb2e4c26ceb2394d6e6185cbb4b48101addcdc Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sat, 14 Nov 2026 15:54:31 +0000 Subject: [PATCH 09/13] fix(desktop-gpui): end only the confirmed unresponsive Cap, by pidfd on Linux --- apps/desktop-gpui/Cargo.toml | 2 - apps/desktop-gpui/src/single_instance.rs | 375 ++++++++++++++--------- 2 files changed, 232 insertions(+), 145 deletions(-) diff --git a/apps/desktop-gpui/Cargo.toml b/apps/desktop-gpui/Cargo.toml index 8ef6eaf6abc..a39d6dc923a 100644 --- a/apps/desktop-gpui/Cargo.toml +++ b/apps/desktop-gpui/Cargo.toml @@ -215,12 +215,10 @@ windows-sys = { version = "0.59", features = [ "Win32_Storage_FileSystem", "Win32_System_Console", "Win32_System_Diagnostics_Debug", - "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Registry", - "Win32_System_RemoteDesktop", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_UI_Shell", diff --git a/apps/desktop-gpui/src/single_instance.rs b/apps/desktop-gpui/src/single_instance.rs index 4d8192d9d2d..b06cd3317b6 100644 --- a/apps/desktop-gpui/src/single_instance.rs +++ b/apps/desktop-gpui/src/single_instance.rs @@ -100,8 +100,14 @@ pub fn acquire() { /// An instance that exited between the pidfile read and the reopen is simply /// gone. One that is still alive and did not answer is hung, and the user /// decides whether to end it; exiting quietly left them with no Cap at all. +/// The pidfd is taken before the prompt, so however long the prompt stays up +/// a reused pid can never receive the signal. #[cfg(target_os = "linux")] fn take_over_from_unresponsive_linux_instance(pid: i32) { + let Ok(process) = LinuxProcess::open(pid) else { + tracing::info!(pid, "the previous Cap GPUI exited; starting a new one"); + return; + }; if !is_cap_gpui(pid) { tracing::info!(pid, "the previous Cap GPUI exited; starting a new one"); return; @@ -109,7 +115,7 @@ fn take_over_from_unresponsive_linux_instance(pid: i32) { if !crate::startup::confirm_quit_unresponsive() { crate::startup::exit(0); } - if !end_linux_instance(pid, || is_cap_gpui(pid)) { + if !end_linux_instance(&process) { crate::startup::fail(format!( "The copy of Cap that isn't responding (process {pid}) could not be quit." )); @@ -118,25 +124,68 @@ fn take_over_from_unresponsive_linux_instance(pid: i32) { } #[cfg(target_os = "linux")] -fn end_linux_instance(pid: i32, alive: impl Fn() -> bool) -> bool { - let exited_within = |limit: std::time::Duration| { - let started = std::time::Instant::now(); - loop { - if !alive() { - return true; - } - if started.elapsed() >= limit { - return false; - } - std::thread::sleep(std::time::Duration::from_millis(50)); +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()) } - }; - unsafe { libc::kill(pid, libc::SIGTERM) }; - if exited_within(std::time::Duration::from_secs(3)) { - return true; } - unsafe { libc::kill(pid, libc::SIGKILL) }; - exited_within(std::time::Duration::from_secs(3)) + + 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. @@ -1087,7 +1136,8 @@ fn acquire_windows_instance(path: &Path) { .chain(std::iter::once(0)) .collect::>(); - let mut ended_unresponsive = false; + 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() }; @@ -1102,35 +1152,34 @@ fn acquire_windows_instance(path: &Path) { let handed_off = hand_off_to_windows_instance(path); let _ = unsafe { CloseHandle(mutex) }; - let unresponsive = match handed_off { + let pid = match handed_off { Ok(()) => crate::startup::exit(0), - Err(pid) => pid, - }; - if ended_unresponsive { - crate::startup::fail( - "Another copy of Cap is still running and could not be quit. Restart your computer, then open Cap again.", - ); - } - tracing::warn!( - pid = ?unresponsive, - "the running Cap GPUI did not answer the reopen request" - ); - if !crate::startup::confirm_quit_unresponsive() { - crate::startup::exit(0); - } - let pids = match unresponsive { - Some(pid) => vec![pid], - None => other_windows_instances(), + 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.", + ), }; - for pid in pids { - 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") + 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); } + confirmed = Some(pid); } + 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." + )), } - ended_unresponsive = true; }; if INSTANCE_MUTEX.set(mutex as usize).is_err() { @@ -1143,13 +1192,41 @@ fn acquire_windows_instance(path: &Path) { } } +#[cfg(any(windows, 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, 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 -/// responsive instance acknowledges a reopen from its listener thread within -/// milliseconds, so a failed reopen means its process is stuck; activating +/// failed reopen means the instance's listener thread is stuck; activating /// its window then showed nothing and the new launch exited without a trace. -/// A Cap whose window still answers messages (a build without the reopen -/// endpoint, or one whose pidfile could not be written) is activated as -/// before, so a working instance is never offered for quitting. +/// 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; @@ -1160,30 +1237,28 @@ fn hand_off_to_windows_instance(path: &Path) -> Result<(), Option> { } std::thread::sleep(std::time::Duration::from_millis(50)); } - if let Some(pid) = identified { - tracing::info!(pid, "Cap GPUI is already running; bringing it forward"); - if forward_windows_deep_links(path, pid) { - activate_windows_instance(pid); - return Ok(()); - } - match reopen_windows_instance(path, pid) { - Ok(()) => return Ok(()), - Err(error) => tracing::warn!(%error, "could not reopen the running Cap GPUI"), - } - } - let candidates = match identified { - Some(pid) => vec![pid], - None => other_windows_instances(), + let Some(pid) = identified else { + return Err(None); }; - for pid in candidates { - if let Some(window) = windows_instance_window(pid) - && windows_window_responds(window) - { - activate_windows_window(window); - return Ok(()); + 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)), } - Err(identified) } #[cfg(windows)] @@ -1193,53 +1268,17 @@ fn windows_window_responds(window: windows_sys::Win32::Foundation::HWND) -> bool }; let mut result = 0; - unsafe { SendMessageTimeoutW(window, WM_NULL, 0, 0, SMTO_ABORTIFHUNG, 2000, &mut result) != 0 } -} - -/// Every other Cap process in this logon session: the mutex is per session, -/// and an instance whose pidfile was lost still holds it. -#[cfg(windows)] -fn other_windows_instances() -> Vec { - use windows_sys::Win32::{ - Foundation::{CloseHandle, INVALID_HANDLE_VALUE}, - System::{ - Diagnostics::ToolHelp::{ - CreateToolhelp32Snapshot, PROCESSENTRY32W, Process32FirstW, Process32NextW, - TH32CS_SNAPPROCESS, - }, - RemoteDesktop::ProcessIdToSessionId, - }, - }; - - let own_pid = std::process::id(); - let mut own_session = 0; - if unsafe { ProcessIdToSessionId(own_pid, &mut own_session) } == 0 { - return Vec::new(); - } - let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) }; - if snapshot == INVALID_HANDLE_VALUE { - return Vec::new(); - } - let mut pids = Vec::new(); - let mut entry = PROCESSENTRY32W { - dwSize: std::mem::size_of::() as u32, - ..unsafe { std::mem::zeroed() } - }; - let mut more = unsafe { Process32FirstW(snapshot, &mut entry) } != 0; - while more { - let pid = entry.th32ProcessID; - let mut session = 0; - if pid != own_pid - && unsafe { ProcessIdToSessionId(pid, &mut session) } != 0 - && session == own_session - && windows_process_is_cap(pid) - { - pids.push(pid); - } - more = unsafe { Process32NextW(snapshot, &mut entry) } != 0; + unsafe { + SendMessageTimeoutW( + window, + WM_NULL, + 0, + 0, + SMTO_ABORTIFHUNG, + WINDOW_RESPONSE_TIMEOUT_MS, + &mut result, + ) != 0 } - let _ = unsafe { CloseHandle(snapshot) }; - pids } #[cfg(windows)] @@ -1252,13 +1291,14 @@ fn end_windows_process(pid: u32) -> std::io::Result<()> { }, }; - if !windows_process_is_cap(pid) { - return Ok(()); - } 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 { @@ -1513,10 +1553,23 @@ 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 pid = std::fs::read_to_string(path).ok()?.trim().parse().ok()?; - windows_process_is_cap(pid).then_some(pid) + 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)] @@ -3328,12 +3381,29 @@ mod windows_takeover_tests { 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())); - assert!(other_windows_instances().contains(&fake.pid())); - assert!(!other_windows_instances().contains(&std::process::id())); end_windows_process(fake.pid()).unwrap(); assert!(exited(&mut fake.child)); assert!(!windows_process_is_cap(fake.pid())); @@ -3346,7 +3416,6 @@ mod windows_takeover_tests { .stdout(std::process::Stdio::null()) .spawn() .unwrap(); - assert!(!other_windows_instances().contains(&other.id())); end_windows_process(other.id()).unwrap(); assert!(!exited(&mut other)); other.kill().unwrap(); @@ -3359,38 +3428,44 @@ mod linux_takeover_tests { use super::*; use std::time::{Duration, Instant}; - fn alive(child: &std::sync::Mutex) -> bool { - child.lock().unwrap().try_wait().unwrap().is_none() - } - #[test] fn a_hung_instance_is_ended_with_sigterm() { - let child = std::sync::Mutex::new( - std::process::Command::new("sleep") - .arg("60") - .spawn() - .unwrap(), - ); - let pid = child.lock().unwrap().id() as i32; + 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(pid, || alive(&child))); + 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 child = std::sync::Mutex::new( - std::process::Command::new("sh") - .args(["-c", "trap '' TERM; while :; do sleep 1; done"]) - .spawn() - .unwrap(), - ); - let pid = child.lock().unwrap().id() as i32; + 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(pid, || alive(&child))); + 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)); } #[test] @@ -3401,3 +3476,17 @@ mod linux_takeover_tests { take_over_from_unresponsive_linux_instance(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); + } +} From ed3074f690eac9b1213835c3a325118f33e204ed Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:12:28 +0000 Subject: [PATCH 10/13] fix(desktop-gpui): treat only ESRCH from pidfd_open as an exited Cap --- apps/desktop-gpui/src/single_instance.rs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/apps/desktop-gpui/src/single_instance.rs b/apps/desktop-gpui/src/single_instance.rs index b06cd3317b6..dc9021d6adc 100644 --- a/apps/desktop-gpui/src/single_instance.rs +++ b/apps/desktop-gpui/src/single_instance.rs @@ -104,9 +104,15 @@ pub fn acquire() { /// a reused pid can never receive the signal. #[cfg(target_os = "linux")] fn take_over_from_unresponsive_linux_instance(pid: i32) { - let Ok(process) = LinuxProcess::open(pid) else { - tracing::info!(pid, "the previous Cap GPUI exited; starting a new one"); - return; + let process = match LinuxProcess::open(pid) { + Ok(process) => process, + Err(error) if error.raw_os_error() == Some(libc::ESRCH) => { + tracing::info!(pid, "the previous Cap GPUI exited; starting a new one"); + return; + } + Err(error) => crate::startup::fail(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) { tracing::info!(pid, "the previous Cap GPUI exited; starting a new one"); From abde02399c273eb6b344137056afbc2dbfbfb763 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:38:16 +0000 Subject: [PATCH 11/13] fix(desktop-gpui): serialize Linux recovery and keep a Cap that answers after the prompt --- apps/desktop-gpui/src/single_instance.rs | 322 +++++++++++++++++++---- 1 file changed, 277 insertions(+), 45 deletions(-) diff --git a/apps/desktop-gpui/src/single_instance.rs b/apps/desktop-gpui/src/single_instance.rs index dc9021d6adc..254a6bfe459 100644 --- a/apps/desktop-gpui/src/single_instance.rs +++ b/apps/desktop-gpui/src/single_instance.rs @@ -59,23 +59,15 @@ pub fn acquire() { #[cfg(windows)] 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"); - crate::startup::exit(0); - } - Err(error) => { - tracing::warn!(pid, %error, "The running Cap GPUI did not answer the reopen request"); - take_over_from_unresponsive_linux_instance(pid); - } - } - } + 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() { @@ -97,36 +89,122 @@ pub fn acquire() { } } -/// An instance that exited between the pidfile read and the reopen is simply -/// gone. One that is still alive and did not answer is hung, and the user -/// decides whether to end it; exiting quietly left them with no Cap at all. +#[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 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 take_over_from_unresponsive_linux_instance(pid: i32) { - let process = match LinuxProcess::open(pid) { - Ok(process) => process, - Err(error) if error.raw_os_error() == Some(libc::ESRCH) => { - tracing::info!(pid, "the previous Cap GPUI exited; starting a new one"); - return; +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." + )); + } } - Err(error) => crate::startup::fail(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) { - tracing::info!(pid, "the previous Cap GPUI exited; starting a new one"); - return; } - if !crate::startup::confirm_quit_unresponsive() { - crate::startup::exit(0); +} + +#[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)?; } - if !end_linux_instance(&process) { - crate::startup::fail(format!( - "The copy of Cap that isn't responding (process {pid}) could not be quit." - )); + 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); + } } - tracing::info!(pid, "ended the unresponsive Cap GPUI"); } #[cfg(target_os = "linux")] @@ -1198,7 +1276,7 @@ fn acquire_windows_instance(path: &Path) { } } -#[cfg(any(windows, test))] +#[cfg(any(windows, target_os = "linux", test))] #[derive(Debug, PartialEq, Eq)] enum TakeoverStep { Ask, @@ -1209,7 +1287,7 @@ enum TakeoverStep { /// 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, test))] +#[cfg(any(windows, target_os = "linux", test))] fn takeover_step(pid: u32, confirmed: Option, ended: Option) -> TakeoverStep { if ended == Some(pid) { TakeoverStep::GiveUp @@ -3474,12 +3552,166 @@ mod linux_takeover_tests { 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(); + let child = std::process::Command::new(&image) + .arg("60") + .spawn() + .unwrap(); + let fake = Self(child); + let started = Instant::now(); + 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(); - let pid = child.id() as i32; + std::fs::write(&path, child.id().to_string()).unwrap(); child.wait().unwrap(); - take_over_from_unresponsive_linux_instance(pid); + 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()); } } From e6f46cbfb97ab0d07a20176640f2f9d2d53b2e98 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:48:02 +0000 Subject: [PATCH 12/13] test(desktop-gpui): retry the fake Cap spawn while a parallel fork holds the copy --- apps/desktop-gpui/src/single_instance.rs | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/apps/desktop-gpui/src/single_instance.rs b/apps/desktop-gpui/src/single_instance.rs index 254a6bfe459..855a1617fd5 100644 --- a/apps/desktop-gpui/src/single_instance.rs +++ b/apps/desktop-gpui/src/single_instance.rs @@ -3560,12 +3560,23 @@ mod linux_takeover_tests { let image = directory.join(name).join("cap-gpui"); std::fs::create_dir_all(image.parent().unwrap()).unwrap(); std::fs::copy("/bin/sleep", &image).unwrap(); - let child = std::process::Command::new(&image) - .arg("60") - .spawn() - .unwrap(); - let fake = Self(child); + // 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)); From 8070639e9f954a76cdd5a287d18b43309643a1aa Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:24:13 +0000 Subject: [PATCH 13/13] fix(desktop-gpui): let one Windows launch at a time recover a frozen Cap Two launches recovering the same frozen copy could both stop with "could not be reached": each opened the instance mutex to check on the copy, so whichever launch ended it found the mutex kept alive by the other launch with no process behind it. Launches of a profile now take turns through an owned Local\CapGpuiLaunch mutex, held until the pidfile and endpoint are published, so only the holder ever opens the instance mutex and the next launch hands off to the copy it started. A holder that dies leaves the lock abandoned, which counts as free. Also expect the Linux launch lock file in the first-launch profile test. --- apps/desktop-gpui/src/single_instance.rs | 134 ++++++++++++++++++++++- 1 file changed, 130 insertions(+), 4 deletions(-) diff --git a/apps/desktop-gpui/src/single_instance.rs b/apps/desktop-gpui/src/single_instance.rs index 855a1617fd5..11d1c98e15c 100644 --- a/apps/desktop-gpui/src/single_instance.rs +++ b/apps/desktop-gpui/src/single_instance.rs @@ -57,7 +57,7 @@ pub fn acquire() { } } #[cfg(windows)] - acquire_windows_instance(&path); + let _launch_lock = acquire_windows_instance(&path); #[cfg(target_os = "linux")] let _launch_lock = match acquire_linux_instance( &path, @@ -1205,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}, @@ -1215,7 +1217,14 @@ 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::>(); @@ -1274,6 +1283,52 @@ fn acquire_windows_instance(path: &Path) { if let Err(error) = start_deep_link_forwarding(path) { 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))] @@ -1936,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")] @@ -3493,6 +3559,66 @@ mod windows_takeover_tests { 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")