diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.toml index f8d439fd63..b19f8eca52 100644 --- a/desktop/src-tauri/Cargo.toml +++ b/desktop/src-tauri/Cargo.toml @@ -123,7 +123,9 @@ objc2 = { version = "0.6", features = ["exception"] } # Narration on the Mac: on-device speech recognition from the microphone. See `speech/macos.rs`. # The same objc2 generation Tauri and wry already use. block2 = "0.6" -objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSError", "NSLocale", "NSOperation", "NSString"] } +# `NSFileManager` and `NSURL`: the copy of OpenBot a move to Applications replaces, put in the Trash +# (`app_location`). +objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSError", "NSFileManager", "NSLocale", "NSOperation", "NSString", "NSURL"] } objc2-speech = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-avf-audio", "SFSpeechRecognizer", "SFSpeechRecognitionRequest", "SFSpeechRecognitionResult", "SFSpeechRecognitionTask", "SFTranscription"] } objc2-avf-audio = { version = "0.3", default-features = false, features = ["std", "block2", "AVAudioEngine", "AVAudioNode", "AVAudioIONode", "AVAudioFormat", "AVAudioBuffer", "AVAudioTime", "AVAudioTypes"] } objc2-av-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "AVCaptureDevice", "AVMediaFormat"] } diff --git a/desktop/src-tauri/src/app_location.rs b/desktop/src-tauri/src/app_location.rs new file mode 100644 index 0000000000..9dcabc90c6 --- /dev/null +++ b/desktop/src-tauri/src/app_location.rs @@ -0,0 +1,773 @@ +/*! +Where this OpenBot app runs from on a Mac, and the move into Applications when that place can't take +an update. + +The updater installs a new version by swapping the app bundle in place, with a temporary folder next +to it. Two places a Mac app can run from are read-only, so that install fails with "Read-only file +system (os error 30)", after the whole update has downloaded: + +- the disk image it came on, mounted under `/Volumes`, when somebody opens OpenBot from it without + dragging it into Applications first; +- a Gatekeeper translocation: a quarantined app that Finder did not move runs from a random, + read-only copy under `AppTranslocation`. + +The leading Mac apps handle this the same way. Electron's `app.moveToApplicationsFolder()` and Sparkle +apps that use LetsMove offer one press that copies the app into Applications, lifts its quarantine, +puts the copy it replaces in the Trash, and opens the moved app, ejecting the disk image it came on. +Sparkle and Squirrel refuse to update from a read-only volume. OpenBot offers that move at launch and +again when somebody asks to update. + +On Windows and Linux there is nothing to move: `place` always finds OpenBot `Fine` there. +*/ + +use std::path::{Path, PathBuf}; + +use crate::app_update::Prompt; + +/// Where the running app is, as far as an update is concerned. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Place { + /// Somewhere the updater can replace it, or not an app bundle at all (a development build). + Fine, + /// On a disk image, or another read-only volume: `bundle` is the app, `volume` where that + /// volume is mounted, ejected after the move when it is a disk image. + DiskImage { bundle: PathBuf, volume: PathBuf }, + /// A read-only copy Gatekeeper runs in place of the app at `original`. + Translocated { bundle: PathBuf, original: PathBuf }, +} + +impl Place { + /// Whether the updater can't install here, so OpenBot asks to move first. + pub fn needs_move(&self) -> bool { + !matches!(self, Place::Fine) + } + + /// The app bundle the move copies. + fn bundle(&self) -> Option<&Path> { + match self { + Place::Fine => None, + Place::DiskImage { bundle, .. } | Place::Translocated { bundle, .. } => Some(bundle), + } + } +} + +/// What `statfs` says of the file system a path is on. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Mount { + /// Where it is mounted (`f_mntonname`). + pub on: PathBuf, + /// What is mounted there (`f_mntfromname`): a device, or for a translocation the real folder. + pub from: PathBuf, + pub read_only: bool, +} + +/// The file system `path` is on, from `statfs`. None when it can't be read. +#[cfg(target_os = "macos")] +pub fn mount_of(path: &Path) -> Option { + use std::os::unix::ffi::OsStrExt as _; + let path = std::ffi::CString::new(path.as_os_str().as_bytes()).ok()?; + let mut mount = std::mem::MaybeUninit::::uninit(); + // SAFETY: `path` is NUL-terminated and `mount` is a valid place for one `statfs` to be written. + if unsafe { libc::statfs(path.as_ptr(), mount.as_mut_ptr()) } != 0 { + return None; + } + // SAFETY: `statfs` returned 0, so it filled `mount`. + let mount = unsafe { mount.assume_init() }; + let text = |chars: &[libc::c_char]| { + // SAFETY: both fields are fixed arrays the kernel NUL-terminates. + let said = unsafe { std::ffi::CStr::from_ptr(chars.as_ptr()) }; + PathBuf::from(std::ffi::OsStr::from_bytes(said.to_bytes())) + }; + Some(Mount { + on: text(&mount.f_mntonname), + from: text(&mount.f_mntfromname), + read_only: mount.f_flags & libc::MNT_RDONLY as u32 != 0, + }) +} + +#[cfg(not(target_os = "macos"))] +pub fn mount_of(_path: &Path) -> Option { + None +} + +/// The `.app` bundle that holds `exe`, the nearest folder above it whose name ends in `.app`. +pub fn bundle_of(exe: &Path) -> Option { + exe.ancestors() + .skip(1) + .find(|folder| folder.extension().is_some_and(|ext| ext == "app")) + .map(Path::to_path_buf) +} + +/// Where the app that `exe` belongs to runs from. `Fine` off a Mac. +pub fn place(exe: &Path) -> Place { + if cfg!(target_os = "macos") { + place_with(exe, mount_of) + } else { + Place::Fine + } +} + +/// `place`, with how a path's file system is read given, so a test can name any mount. +pub fn place_with(exe: &Path, mount_of: impl Fn(&Path) -> Option) -> Place { + let Some(bundle) = bundle_of(exe) else { + return Place::Fine; + }; + let Some(mount) = mount_of(&bundle) else { + return Place::Fine; + }; + if bundle.to_string_lossy().contains("/AppTranslocation/") { + // The translocation mounts the app's real folder at `/d`; `from` names the app. + let original = crate::recorder_install::untranslocated(&bundle, &mount.on, &mount.from); + return match original { + // Translocated from a disk image: the image is what to eject after the move. + Some(original) => match mount_of(&original) { + Some(theirs) if theirs.read_only => Place::DiskImage { + bundle, + volume: theirs.on, + }, + _ => Place::Translocated { bundle, original }, + }, + None => Place::DiskImage { + volume: mount.on, + bundle, + }, + }; + } + if mount.read_only { + return Place::DiskImage { + bundle, + volume: mount.on, + }; + } + Place::Fine +} + +/// The Applications folder to move into: `/Applications` when this person can write to it, as an +/// admin can, otherwise the `Applications` folder in their home folder, as LetsMove falls back to. +pub fn applications_folder(system: &Path, home: Option<&Path>) -> PathBuf { + if writable(system) { + return system.to_path_buf(); + } + home.map(|home| home.join("Applications")) + .unwrap_or_else(|| system.to_path_buf()) +} + +#[cfg(unix)] +fn writable(folder: &Path) -> bool { + use std::os::unix::ffi::OsStrExt as _; + let Ok(path) = std::ffi::CString::new(folder.as_os_str().as_bytes()) else { + return false; + }; + // SAFETY: `path` is NUL-terminated. + unsafe { libc::access(path.as_ptr(), libc::W_OK) == 0 } +} + +#[cfg(not(unix))] +fn writable(_folder: &Path) -> bool { + false +} + +/// The attribute that marks a downloaded file, and makes Gatekeeper translocate an app that has it. +#[cfg(target_os = "macos")] +const QUARANTINE: &str = "com.apple.quarantine"; + +/// Remove the quarantine from `path` and everything under it, as LetsMove does to the moved app: +/// a copy made with `ditto` keeps it, and Gatekeeper would run that copy translocated again. The +/// app already passed Gatekeeper's check when it was first opened. +#[cfg(target_os = "macos")] +pub fn lift_quarantine(path: &Path) -> std::io::Result<()> { + use std::os::unix::ffi::OsStrExt as _; + let name = std::ffi::CString::new(QUARANTINE).expect("no NUL in the attribute's name"); + let lift = |path: &Path| -> std::io::Result<()> { + let at = + std::ffi::CString::new(path.as_os_str().as_bytes()).map_err(std::io::Error::other)?; + // SAFETY: both strings are NUL-terminated. + if unsafe { libc::removexattr(at.as_ptr(), name.as_ptr(), libc::XATTR_NOFOLLOW) } == 0 { + return Ok(()); + } + let error = std::io::Error::last_os_error(); + match error.raw_os_error() { + Some(libc::ENOATTR) => Ok(()), + _ => Err(std::io::Error::other(format!( + "{}: {error}", + path.display() + ))), + } + }; + let mut folders = vec![path.to_path_buf()]; + while let Some(next) = folders.pop() { + lift(&next)?; + if std::fs::symlink_metadata(&next)?.is_dir() { + for entry in std::fs::read_dir(&next)? { + folders.push(entry?.path()); + } + } + } + Ok(()) +} + +#[cfg(not(target_os = "macos"))] +pub fn lift_quarantine(_path: &Path) -> std::io::Result<()> { + Ok(()) +} + +/// Whether `path` carries the quarantine. +#[cfg(target_os = "macos")] +pub fn quarantined(path: &Path) -> bool { + use std::os::unix::ffi::OsStrExt as _; + let (Ok(at), Ok(name)) = ( + std::ffi::CString::new(path.as_os_str().as_bytes()), + std::ffi::CString::new(QUARANTINE), + ) else { + return false; + }; + // SAFETY: both strings are NUL-terminated; a null buffer asks only for the size. + unsafe { + libc::getxattr( + at.as_ptr(), + name.as_ptr(), + std::ptr::null_mut(), + 0, + 0, + libc::XATTR_NOFOLLOW, + ) >= 0 + } +} + +/// Put `path` in the Trash, where a person can still get it back, as Electron and LetsMove do with +/// the copy a move replaces. +#[cfg(target_os = "macos")] +pub fn trash(path: &Path) -> std::io::Result<()> { + use objc2_foundation::{NSFileManager, NSString, NSURL}; + let url = NSURL::fileURLWithPath(&NSString::from_str(&path.to_string_lossy())); + NSFileManager::defaultManager() + .trashItemAtURL_resultingItemURL_error(&url, None) + .map_err(|error| { + std::io::Error::other(format!( + "{}: {}", + path.display(), + error.localizedDescription() + )) + }) +} + +#[cfg(not(target_os = "macos"))] +pub fn trash(path: &Path) -> std::io::Result<()> { + std::fs::remove_dir_all(path) +} + +/// What a move did: the app in Applications, and the disk image to eject once this copy has quit. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Moved { + pub app: PathBuf, + pub eject: Option, +} + +/** +Copy the app `place` names into `applications`, ready to open. + +The copy is made with `ditto`, which keeps the app's signature, under a hidden name in the same +folder, and its quarantine is lifted. Only then is an app already at the destination put in the Trash +(`trash`) and the copy renamed into its place, so a copy that fails leaves the old app where it was. +A translocated app whose original is already that destination only has its quarantine lifted. A +translocated app's original elsewhere (in Downloads, say) goes to the Trash after the move, as +Electron's move does; that is not worth failing the move over. +*/ +pub fn move_into( + place: &Place, + applications: &Path, + trash: impl Fn(&Path) -> std::io::Result<()>, +) -> Result { + let bundle = place + .bundle() + .ok_or("OpenBot is already somewhere it can update")?; + let name = match place { + Place::Translocated { original, .. } => original.file_name(), + _ => bundle.file_name(), + } + .ok_or("the app has no name")? + .to_owned(); + let app = applications.join(&name); + let eject = match place { + Place::DiskImage { volume, .. } if disk_image_at(volume) => Some(volume.clone()), + _ => None, + }; + if let Place::Translocated { original, .. } = place { + if *original == app { + lift_quarantine(&app).map_err(|error| format!("lifting the quarantine: {error}"))?; + return Ok(Moved { app, eject }); + } + } + std::fs::create_dir_all(applications) + .map_err(|error| format!("{}: {error}", applications.display()))?; + let mut staging_name = std::ffi::OsString::from("."); + staging_name.push(&name); + staging_name.push(".moving"); + let staging = applications.join(staging_name); + if staging.exists() { + std::fs::remove_dir_all(&staging) + .map_err(|error| format!("{}: {error}", staging.display()))?; + } + let copied = std::process::Command::new("/usr/bin/ditto") + .arg(bundle) + .arg(&staging) + .output() + .map_err(|error| format!("ditto: {error}"))?; + if !copied.status.success() { + let _ = std::fs::remove_dir_all(&staging); + return Err(format!( + "ditto {} {}: {}", + bundle.display(), + staging.display(), + String::from_utf8_lossy(&copied.stderr).trim() + )); + } + let ready = lift_quarantine(&staging) + .map_err(|error| format!("lifting the quarantine: {error}")) + .and_then(|()| { + if std::fs::symlink_metadata(&app).is_ok() { + trash(&app).map_err(|error| format!("moving the old app to the Trash: {error}"))?; + } + std::fs::rename(&staging, &app).map_err(|error| format!("{}: {error}", app.display())) + }); + if let Err(error) = ready { + let _ = std::fs::remove_dir_all(&staging); + return Err(error); + } + if let Place::Translocated { original, .. } = place { + if let Err(error) = trash(original) { + log::warn!("[move to Applications] the copy it was moved from stays: {error}"); + } + } + Ok(Moved { app, eject }) +} + +/// Whether `volume` is a mounted disk image, as `hdiutil info` lists them: only a disk image is +/// ejected after the move, never a drive somebody plugged in. +#[cfg(target_os = "macos")] +pub fn disk_image_at(volume: &Path) -> bool { + let Ok(info) = std::process::Command::new("/usr/bin/hdiutil") + .arg("info") + .output() + else { + return false; + }; + let volume = volume.to_string_lossy(); + String::from_utf8_lossy(&info.stdout) + .lines() + .any(|line| line.rsplit('\t').next().map(str::trim_end) == Some(volume.as_ref())) +} + +#[cfg(not(target_os = "macos"))] +pub fn disk_image_at(_volume: &Path) -> bool { + false +} + +/// The script that opens the moved app once this one has quit: it waits for `$1`'s process to +/// end, ejects the disk image in `$3` when there is one, then opens `$2` with `$4`. The paths are +/// arguments, never part of the script, so no name can change what it runs. +const OPEN_AFTER_QUIT: &str = r#"while kill -0 "$1" 2>/dev/null; do sleep 0.2; done +if [ -n "$3" ]; then /usr/bin/hdiutil detach -quiet "$3" || /usr/bin/hdiutil detach -quiet -force "$3"; fi +exec "$4" "$2""#; + +/// Start what opens `moved` once the process `pid` has quit (`OPEN_AFTER_QUIT`), with `opener`: +/// `/usr/bin/open` for the app. +pub fn open_after_quit( + pid: u32, + moved: &Moved, + opener: &Path, +) -> std::io::Result { + std::process::Command::new("/bin/sh") + // Not on the disk image, which could then not be ejected. + .current_dir("/") + .arg("-c") + .arg(OPEN_AFTER_QUIT) + .arg("openbot-move") + .arg(pid.to_string()) + .arg(&moved.app) + .arg(moved.eject.as_deref().unwrap_or(Path::new(""))) + .arg(opener) + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn() +} + +/// The button that moves OpenBot, and the one that leaves it where it is. +pub const MOVE: &str = "Move to Applications"; +pub const NOT_NOW: &str = "Not now"; + +/// Why OpenBot can't update where it is, in a sentence. +fn where_it_is(place: &Place) -> &'static str { + match place { + Place::Translocated { .. } => "macOS is running OpenBot from a temporary copy", + _ => "OpenBot is open from its disk image", + } +} + +/// What OpenBot asks as it opens from a place it can't update in. +pub fn at_launch(place: &Place) -> Prompt { + Prompt { + title: "Move OpenBot to Applications?".into(), + message: format!( + "{}, so it can't update itself. Move it to Applications to keep getting updates.", + where_it_is(place) + ), + buttons: Some((MOVE, NOT_NOW)), + } +} + +/// What OpenBot asks when somebody chose to update it where it can't install, with the +/// version they asked for when it is known. +pub fn at_update(place: &Place, version: Option<&str>) -> Prompt { + Prompt { + title: match version { + Some(version) => format!("OpenBot {version} is available"), + None => "Move OpenBot to Applications to update".into(), + }, + message: format!( + "{}, so it can't update itself. Move it to Applications, then update from there.", + where_it_is(place) + ), + buttons: Some((MOVE, NOT_NOW)), + } +} + +/// Why the update didn't install when somebody chose Not now, after the banner's "Couldn't install +/// the update:". +pub const NOT_MOVED: &str = "OpenBot has to be in Applications to update."; + +/// A move that failed. The person can still do it by hand. +pub fn move_failed() -> Prompt { + Prompt { + title: "OpenBot couldn't move to Applications".into(), + message: "Quit OpenBot and drag it into your Applications folder. Then open it from there." + .into(), + buttons: None, + } +} + +#[cfg(all(test, target_os = "macos"))] +mod tests { + use super::*; + + /// A folder of its own for one test, removed when it ends. + struct Scratch(PathBuf); + + impl Scratch { + fn new(name: &str) -> Self { + let folder = std::env::temp_dir().join(format!( + "openbot-app-location-{name}-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&folder); + std::fs::create_dir_all(&folder).unwrap(); + // The real path: `/var` is a link to `/private/var`, and `statfs` and `hdiutil` say the + // real one. + Self(folder.canonicalize().unwrap()) + } + } + + impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + /// A small app bundle with an executable, quarantined as a download is. + fn fake_app(folder: &Path, quarantine: bool) -> PathBuf { + let app = folder.join("OpenBot.app"); + let macos = app.join("Contents/MacOS"); + std::fs::create_dir_all(&macos).unwrap(); + std::fs::write(app.join("Contents/Info.plist"), "").unwrap(); + std::fs::write(macos.join("openbot-desktop"), "#!/bin/sh\n").unwrap(); + if quarantine { + let marked = std::process::Command::new("/usr/bin/xattr") + .args(["-w", QUARANTINE, "0083;00000000;Safari;"]) + .arg(&app) + .status() + .unwrap(); + assert!(marked.success()); + } + app + } + + /// A real disk image holding `app`, mounted read-only as Finder mounts a downloaded one, and + /// ejected when the test ends. + struct DiskImage { + volume: PathBuf, + } + + impl DiskImage { + fn holding(scratch: &Path, app_folder: &Path) -> Self { + let image = scratch.join("OpenBot.dmg"); + let made = std::process::Command::new("/usr/bin/hdiutil") + .args(["create", "-quiet", "-fs", "HFS+", "-volname", "OpenBot"]) + .arg("-srcfolder") + .arg(app_folder) + .arg(&image) + .status() + .unwrap(); + assert!(made.success(), "hdiutil create"); + let volume = scratch.join("mounted"); + std::fs::create_dir_all(&volume).unwrap(); + let attached = std::process::Command::new("/usr/bin/hdiutil") + .args(["attach", "-quiet", "-readonly", "-nobrowse", "-mountpoint"]) + .arg(&volume) + .arg(&image) + .status() + .unwrap(); + assert!(attached.success(), "hdiutil attach"); + Self { volume } + } + } + + impl Drop for DiskImage { + fn drop(&mut self) { + if disk_image_at(&self.volume) { + let _ = std::process::Command::new("/usr/bin/hdiutil") + .args(["detach", "-quiet", "-force"]) + .arg(&self.volume) + .status(); + } + } + } + + fn exe_in(app: &Path) -> PathBuf { + app.join("Contents/MacOS/openbot-desktop") + } + + /** + Ben's report, 2026-12-04: OpenBot 1.2.3 opened from its disk image could not install 1.2.11 + from the banner or Check for Updates…, with "Read-only file system (os error 30) at path + "/Volumes/OpenBot/tauri_current_app…"". The updater makes that temporary folder next to the + app (`tempfile::Builder::tempdir_in`, as here) and a disk image is read-only. + + This one mounts a real disk image read-only, finds the app on it needs to move, moves it into + an Applications folder, and shows the moved app is somewhere the updater's folder can be made, + with its quarantine lifted so Gatekeeper does not translocate it again. + */ + #[test] + fn an_app_open_from_its_disk_image_is_moved_somewhere_it_can_update() { + let scratch = Scratch::new("disk-image"); + let source = scratch.0.join("source"); + std::fs::create_dir_all(&source).unwrap(); + fake_app(&source, true); + let image = DiskImage::holding(&scratch.0, &source); + let on_image = image.volume.join("OpenBot.app"); + + // What the updater met: its temporary folder can't be made next to the app. + let staged = std::fs::create_dir(image.volume.join("tauri_current_app")); + assert_eq!( + staged.unwrap_err().raw_os_error(), + Some(libc::EROFS), + "a disk image is read-only" + ); + assert!( + quarantined(&on_image), + "the image keeps the download's quarantine" + ); + + let place = place(&exe_in(&on_image)); + assert_eq!( + place, + Place::DiskImage { + bundle: on_image.clone(), + volume: image.volume.clone(), + } + ); + assert!(place.needs_move()); + + let applications = scratch.0.join("Applications"); + let moved = move_into(&place, &applications, |_| panic!("nothing to replace")).unwrap(); + assert_eq!( + moved, + Moved { + app: applications.join("OpenBot.app"), + eject: Some(image.volume.clone()), + } + ); + assert!(exe_in(&moved.app).is_file()); + assert!( + !quarantined(&moved.app), + "the moved app is not translocated again" + ); + assert_eq!(super::place(&exe_in(&moved.app)), Place::Fine); + std::fs::create_dir(applications.join("tauri_current_app")) + .expect("the updater can stage an install next to the moved app"); + } + + /// An app already in Applications is replaced, and the old one goes to the Trash, not away. + #[test] + fn a_move_puts_the_app_it_replaces_in_the_trash() { + let scratch = Scratch::new("replace"); + let source = scratch.0.join("source"); + std::fs::create_dir_all(&source).unwrap(); + fake_app(&source, false); + let image = DiskImage::holding(&scratch.0, &source); + let applications = scratch.0.join("Applications"); + std::fs::create_dir_all(&applications).unwrap(); + let old = fake_app(&applications, false); + std::fs::write(old.join("Contents/old"), "1.2.2").unwrap(); + let trash_folder = scratch.0.join("Trash"); + std::fs::create_dir_all(&trash_folder).unwrap(); + + let place = place(&exe_in(&image.volume.join("OpenBot.app"))); + let moved = move_into(&place, &applications, |replaced| { + std::fs::rename(replaced, trash_folder.join("OpenBot.app")) + }) + .unwrap(); + + assert!( + !moved.app.join("Contents/old").exists(), + "the new app is in place" + ); + assert!(trash_folder.join("OpenBot.app/Contents/old").exists()); + } + + /// A copy that fails leaves the app in Applications as it was. + #[test] + fn a_failed_move_leaves_the_old_app() { + let scratch = Scratch::new("failed"); + let applications = scratch.0.join("Applications"); + std::fs::create_dir_all(&applications).unwrap(); + let old = fake_app(&applications, false); + let gone = Place::DiskImage { + bundle: scratch.0.join("missing/OpenBot.app"), + volume: scratch.0.join("missing"), + }; + assert!(move_into(&gone, &applications, |_| panic!("not reached")).is_err()); + assert!(exe_in(&old).is_file()); + assert!(!applications.join(".OpenBot.app.moving").exists()); + } + + /// Gatekeeper's translocation: the app runs from `/d/OpenBot.app`, a read-only copy of + /// the one in Downloads. That one is moved, and the Downloads copy goes to the Trash. When the + /// original is already in Applications, only its quarantine is lifted. + #[test] + fn a_translocated_app_is_moved_from_where_it_really_is() { + let scratch = Scratch::new("translocated"); + let downloads = scratch.0.join("Downloads"); + std::fs::create_dir_all(&downloads).unwrap(); + let original = fake_app(&downloads, true); + let mount = PathBuf::from("/private/var/folders/x/T/AppTranslocation/ABC"); + let running = mount.join("d/OpenBot.app/Contents/MacOS/openbot-desktop"); + let translocated = |path: &Path| { + if path.starts_with(&mount) { + Some(Mount { + on: mount.clone(), + from: original.clone(), + read_only: true, + }) + } else { + mount_of(path) + } + }; + let place = place_with(&running, translocated); + assert_eq!( + place, + Place::Translocated { + bundle: mount.join("d/OpenBot.app"), + original: original.clone(), + } + ); + + // The translocated copy reads as the original does; here that is the original itself. + let readable = Place::Translocated { + bundle: original.clone(), + original: original.clone(), + }; + let applications = scratch.0.join("Applications"); + let trashed = std::sync::Mutex::new(Vec::new()); + let moved = move_into(&readable, &applications, |path| { + trashed.lock().unwrap().push(path.to_path_buf()); + Ok(()) + }) + .unwrap(); + assert_eq!(moved.app, applications.join("OpenBot.app")); + assert_eq!(moved.eject, None); + assert!(!quarantined(&moved.app)); + assert_eq!(*trashed.lock().unwrap(), vec![original.clone()]); + + // Already in Applications, but quarantined: nothing is copied or trashed. + let in_place = fake_app(&scratch.0.join("Applications2"), true); + let already = Place::Translocated { + bundle: mount.join("d/OpenBot.app"), + original: in_place.clone(), + }; + let moved = move_into(&already, &scratch.0.join("Applications2"), |_| { + panic!("nothing to trash") + }) + .unwrap(); + assert_eq!(moved.app, in_place); + assert!(!quarantined(&in_place)); + } + + /// An app somewhere writable, such as Applications or a development build's folder, stays. + #[test] + fn an_app_somewhere_writable_or_no_app_at_all_is_fine() { + let scratch = Scratch::new("fine"); + let app = fake_app(&scratch.0, false); + assert_eq!(place(&exe_in(&app)), Place::Fine); + assert_eq!( + place(Path::new("/Users/a/openbot/target/debug/openbot-desktop")), + Place::Fine + ); + } + + /// Once this copy has quit, the moved app opens and the disk image it came on is ejected. + #[test] + fn the_moved_app_opens_after_this_one_quits_and_the_image_is_ejected() { + let scratch = Scratch::new("open-after"); + let source = scratch.0.join("source"); + std::fs::create_dir_all(&source).unwrap(); + fake_app(&source, false); + let image = DiskImage::holding(&scratch.0, &source); + assert!(disk_image_at(&image.volume)); + + let mut running = std::process::Command::new("/bin/sleep") + .arg("1") + .spawn() + .unwrap(); + let opened = scratch.0.join("opened"); + let moved = Moved { + app: opened.clone(), + eject: Some(image.volume.clone()), + }; + // `touch` stands in for `open`, and writes the path it was given. + let mut after = open_after_quit(running.id(), &moved, Path::new("/usr/bin/touch")).unwrap(); + assert!(!opened.exists(), "nothing opens while this copy runs"); + running.wait().unwrap(); + assert!(after.wait().unwrap().success()); + assert!(opened.exists()); + assert!(!disk_image_at(&image.volume), "the disk image is ejected"); + } + + /// The words, as `openbot-copy` has them. + #[test] + fn the_prompts_say_where_openbot_is_and_what_to_press() { + let image = Place::DiskImage { + bundle: "/Volumes/OpenBot/OpenBot.app".into(), + volume: "/Volumes/OpenBot".into(), + }; + let launch = at_launch(&image); + assert_eq!(launch.title, "Move OpenBot to Applications?"); + assert_eq!( + launch.message, + "OpenBot is open from its disk image, so it can't update itself. Move it to Applications to keep getting updates." + ); + assert_eq!(launch.buttons, Some(("Move to Applications", "Not now"))); + let update = at_update(&image, Some("1.2.11")); + assert_eq!(update.title, "OpenBot 1.2.11 is available"); + assert!(update + .message + .ends_with("Move it to Applications, then update from there.")); + let translocated = Place::Translocated { + bundle: "/private/var/folders/x/AppTranslocation/A/d/OpenBot.app".into(), + original: "/Users/a/Downloads/OpenBot.app".into(), + }; + assert!(at_launch(&translocated) + .message + .starts_with("macOS is running OpenBot from a temporary copy")); + } +} diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs index b2b0d2829f..2302652c0d 100644 --- a/desktop/src-tauri/src/lib.rs +++ b/desktop/src-tauri/src/lib.rs @@ -1,6 +1,7 @@ //! The parts of the shell that are worth testing without a window around them. pub mod acquire; pub mod ai_connection; +pub mod app_location; pub mod app_update; pub mod backoff; pub mod chatgpt_sign_in; diff --git a/desktop/src-tauri/src/main.rs b/desktop/src-tauri/src/main.rs index 368a5d221e..7c1229abaf 100644 --- a/desktop/src-tauri/src/main.rs +++ b/desktop/src-tauri/src/main.rs @@ -28,9 +28,9 @@ mod zoom; mod test_support; use openbot_desktop_lib::{ - acquire, app_update, deployment, deployment_release, docker_config, early_downloads, engine, - engine_versions, env as openbot_env, harness, host_access, install, local_eval, - local_eval_state, logging, machine_size, own_machine, preparation, + acquire, app_location, app_update, deployment, deployment_release, docker_config, + early_downloads, engine, engine_versions, env as openbot_env, harness, host_access, install, + local_eval, local_eval_state, logging, machine_size, own_machine, preparation, problem::{LeftoverReset, Problem}, provider, pull_metrics, quiet, recorder_external, recorder_host, recorder_install, security_floor, stack, superseded_images, telemetry, tray, troubleshooting, uninstall, @@ -3297,6 +3297,19 @@ fn check_for_updates_from_menu(app: tauri::AppHandle) { Ok(app_update::Asked::Available { version, .. }) => Some(version.clone()), _ => None, }; + // Open from its disk image or a translocated copy, OpenBot can't install the update where + // it is: the offer is to move first, in one dialog. + let place = this_app_place(); + if let (Some(version), true) = (&offered, place.needs_move()) { + let answering = app.clone(); + let prompt = app_location::at_update(&place, Some(version)); + show_prompt(&app, prompt, move |go| { + if go { + tauri::async_runtime::spawn(move_for_update(answering, place)); + } + }); + return; + } let answering = app.clone(); show_prompt(&app, app_update::prompt(&asked), move |update| { let Some(version) = offered else { @@ -3664,6 +3677,161 @@ fn quit_done_for_restart(quit: &QuitState) { *quit.phase.lock().unwrap() = QuitPhase::Complete(tauri::RESTART_EXIT_CODE); } +/// Where this running app is, as far as an update is concerned (`app_location`). +fn this_app_place() -> app_location::Place { + match std::env::current_exe() { + Ok(exe) => app_location::place(&exe), + Err(error) => { + log::warn!("[move to Applications] could not read where OpenBot runs from: {error}"); + app_location::Place::Fine + } + } +} + +/** +Copy this app into Applications (`app_location::move_into`) and start what opens the moved app once +this one has quit, ejecting the disk image it came on (`app_location::open_after_quit`). The caller +quits. `/Applications` when this person can write to it, or the Applications folder in their home. +*/ +fn move_to_applications(place: &app_location::Place) -> Result { + let home = std::env::var_os("HOME").map(PathBuf::from); + let folder = app_location::applications_folder(Path::new("/Applications"), home.as_deref()); + let moved = app_location::move_into(place, &folder, app_location::trash)?; + app_location::open_after_quit(std::process::id(), &moved, Path::new("/usr/bin/open")) + .map_err(|error| format!("could not start opening {}: {error}", moved.app.display()))?; + log::info!( + "[move to Applications] moved to {}; opening it after this one quits{}", + moved.app.display(), + moved + .eject + .as_ref() + .map(|volume| format!(", then ejecting {}", volume.display())) + .unwrap_or_default() + ); + Ok(moved) +} + +/** +OpenBot open from its disk image, or from a copy Gatekeeper translocated, asks to move to +Applications before anything else opens or starts, as LetsMove asks before an app finishes +launching. Move to Applications moves it, and this copy quits at once: nothing has started yet. Not +now carries on where it is, and the next launch asks again; updating still asks first +(`offer_move_for_update`). +*/ +fn offer_move_at_launch(app: &tauri::AppHandle) { + let place = this_app_place(); + if !place.needs_move() { + return; + } + log::info!("[move to Applications] open from {place:?}; asking at launch"); + #[cfg(target_os = "macos")] + { + let _ = app; + let Some(mtm) = objc2::MainThreadMarker::new() else { + log::error!("[move to Applications] the launch offer was not on the main thread"); + return; + }; + let prompt = app_location::at_launch(&place); + let show = |prompt: app_update::Prompt| { + openbot_desktop_lib::native_alert::ask( + mtm, + &prompt.title, + &prompt.message, + prompt.buttons, + ) + }; + if !show(prompt) { + log::info!("[move to Applications] not now"); + return; + } + match move_to_applications(&place) { + Ok(_) => { + log::logger().flush(); + std::process::exit(0); + } + Err(error) => { + log::error!("[move to Applications] the move failed: {error}"); + show(app_location::move_failed()); + } + } + } + #[cfg(not(target_os = "macos"))] + let _ = app; +} + +/// Update and restart in the banner or the setup window, while OpenBot can't install where it is: +/// the offer to move first. Not now leaves everything as it was, and the banner says to move. +async fn offer_move_for_update( + app: tauri::AppHandle, + place: app_location::Place, +) -> Result<(), Problem> { + let version = app + .state::() + .app_update + .newer() + .map(|v| v.to_string()); + let (answer, answered) = std::sync::mpsc::channel(); + show_prompt( + &app, + app_location::at_update(&place, version.as_deref()), + move |go| { + let _ = answer.send(go); + }, + ); + let go = tauri::async_runtime::spawn_blocking(move || answered.recv().unwrap_or(false)) + .await + .unwrap_or(false); + if !go { + log::info!("[move to Applications] not now, at update"); + return Err(Problem::plain(app_location::NOT_MOVED)); + } + if move_for_update(app, place).await { + Ok(()) + } else { + Err(Problem::plain(app_location::NOT_MOVED)) + } +} + +/** +Move to Applications chosen at update time, with OpenBot running: the copy first, so a copy that +fails leaves everything running as it was, and says so. Then OpenBot is stopped as for an update +(the local backend keeps running), and this copy quits without Quit's cleanup; the moved app opens +once it has, and its Start finds whatever is left. It offers the update again from there. Whether +it moved: when it did, this copy is quitting. +*/ +async fn move_for_update(app: tauri::AppHandle, place: app_location::Place) -> bool { + let guard = match RuntimeUpdateGuard::begin(&app) { + Ok(guard) => guard, + Err(problem) => { + show_prompt(&app, app_update::install_failed(&problem.said), |_| {}); + return false; + } + }; + let moved = tauri::async_runtime::spawn_blocking(move || move_to_applications(&place)) + .await + .map_err(|error| error.to_string()) + .and_then(|moved| moved); + if let Err(error) = moved { + log::error!("[move to Applications] the move failed: {error}"); + show_prompt(&app, app_location::move_failed(), |_| {}); + return false; + } + let handle = app.clone(); + match tauri::async_runtime::spawn_blocking(move || { + stop_for_update(&handle, &stack::default_root()) + }) + .await + { + Ok(Ok(())) => {} + Ok(Err(error)) => log::warn!("[move to Applications] stopping OpenBot first: {error}"), + Err(error) => log::warn!("[move to Applications] stopping OpenBot first: {error}"), + } + drop(guard); + *app.state::().quit.phase.lock().unwrap() = QuitPhase::Complete(0); + app.exit(0); + true +} + /// The setup window's update offer: the same answer the banner in OpenBot's page reads. #[tauri::command] async fn app_update_offer(app: tauri::AppHandle) -> app_update::Status { @@ -3685,6 +3853,10 @@ async fn dismiss_app_update(app: tauri::AppHandle, version: String) -> Result<() #[tauri::command] async fn install_app_update(app: tauri::AppHandle) -> Result<(), Problem> { + let place = this_app_place(); + if place.needs_move() { + return offer_move_for_update(app, place).await; + } install_app_update_now(app).await } @@ -15748,6 +15920,9 @@ fn main() { _ => {} }) .setup(move |app| { + // Open from its disk image or a translocated copy: asked to move to Applications + // before any window opens or anything starts, and quits here if it moves. + offer_move_at_launch(app.handle()); build_main_window(app.handle())?; log_launch(app.handle(), local_offset); desktop_onepassword::start(app.handle()); @@ -21842,9 +22017,9 @@ mod tests { // `held_back` first. let setup = &main[main.find(".setup(move |app| {\n").unwrap()..]; assert!( - setup.starts_with( - ".setup(move |app| {\n build_main_window(app.handle())?;\n log_launch(app.handle(), local_offset);\n" - ), + setup.contains( + "offer_move_at_launch(app.handle());\n build_main_window(app.handle())?;\n log_launch(app.handle(), local_offset);\n" + ) && setup.starts_with(".setup(move |app| {\n // Open from its disk image"), "{}", &setup[..400] ); diff --git a/desktop/src-tauri/src/recorder_install.rs b/desktop/src-tauri/src/recorder_install.rs index ebcd3ff00e..6367471142 100644 --- a/desktop/src-tauri/src/recorder_install.rs +++ b/desktop/src-tauri/src/recorder_install.rs @@ -366,7 +366,11 @@ fn translocation_mount(_path: &Path) -> Option<(PathBuf, PathBuf)> { /// Where a translocated Mac app really is: `/Applications/OpenBot.app/Contents/MacOS/openbot-desktop` /// for `/d/OpenBot.app/Contents/MacOS/openbot-desktop`, when `` holds the app copied /// from `/Applications/OpenBot.app`. None when the path is not inside that mount. -fn untranslocated(current_exe: &Path, mounted_on: &Path, mounted_from: &Path) -> Option { +pub(crate) fn untranslocated( + current_exe: &Path, + mounted_on: &Path, + mounted_from: &Path, +) -> Option { let inside = current_exe.strip_prefix(mounted_on).ok()?; let mut parts = inside.components(); // `d`, then the bundle itself, which the mount's source names.