Open-source AI coworkers that each get a computer of their own: a browser, files and tools, with every action decided before it happens and recorded after. Bring any AG-UI agent.
Fix fresh desktop installation without developer tools (#604)
David McKayd779eaf61799
diff --git a/desktop/src-tauri/Cargo.lock b/desktop/src-tauri/Cargo.lockindex ee05f29b..c66486b5 100644--- a/desktop/src-tauri/Cargo.lock+++ b/desktop/src-tauri/Cargo.lock@@ -47,6 +47,15 @@ version = "1.0.104"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"+[[package]]+name = "arbitrary"+version = "1.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1"+dependencies = [+ "derive_arbitrary",+]+[[package]]name = "async-broadcast"version = "0.7.2"@@ -733,6 +742,17 @@ dependencies = ["serde_core",]+[[package]]+name = "derive_arbitrary"+version = "1.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]+[[package]]name = "derive_more"version = "2.1.1"@@ -2506,6 +2526,7 @@ dependencies = ["tauri-plugin-opener","tauri-plugin-shell","tauri-plugin-single-instance",+ "zip",][[package]]@@ -5699,6 +5720,22 @@ dependencies = ["syn 3.0.5",]+[[package]]+name = "zip"+version = "2.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50"+dependencies = [+ "arbitrary",+ "crc32fast",+ "crossbeam-utils",+ "displaydoc",+ "flate2",+ "indexmap 2.14.2",+ "memchr",+ "thiserror 2.0.20",+]+[[package]]name = "zlib-rs"version = "0.6.7"diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.tomlindex 74e41c4b..eb3b4d2e 100644--- a/desktop/src-tauri/Cargo.toml+++ b/desktop/src-tauri/Cargo.toml@@ -28,6 +28,8 @@ flate2 = "1"# Checking the digest of an installer before running it. See `install.rs`.sha2 = "0.10"tar = "0.4"+# Read Bun's release ZIP in-process; no unzip or PowerShell installation is required.+zip = { version = "2.4.2", default-features = false, features = ["deflate-flate2", "flate2"] }tauri-plugin-single-instance = "2.0.0-rc.5"portable-pty = "0.9.0"tauri-plugin-opener = "2.5.5"diff --git a/desktop/src-tauri/src/engine.rs b/desktop/src-tauri/src/engine.rsindex 9e45d008..4b63842e 100644--- a/desktop/src-tauri/src/engine.rs+++ b/desktop/src-tauri/src/engine.rs@@ -689,3 +689,388 @@ mod tests {);}}++/// A native Podman API service belongs to the desktop session only when this session spawned it.+/// Existing user/systemd services are probed and reused, never stopped or reconfigured.+#[cfg(any(target_os = "linux", all(test, unix)))]+pub mod local_api {+ use crate::problem::Problem;+ use std::io::{Read, Write};+ use std::os::unix::fs::{DirBuilderExt, MetadataExt};+ use std::os::unix::net::UnixStream;+ use std::os::unix::process::CommandExt;+ use std::path::{Path, PathBuf};+ use std::process::{Child, Command, Stdio};+ use std::time::{Duration, Instant};++ #[derive(Default)]+ pub struct Service {+ child: Option<Child>,+ socket: Option<(PathBuf, u64, u64)>,+ }++ fn problem(detail: impl Into<String>) -> Problem {+ Problem::with(+ "OpenBot could not prepare its container API. Try again.",+ detail,+ )+ }++ fn ping(socket: &Path) -> Result<Option<u32>, String> {+ let probe = || -> std::io::Result<(String, Option<u32>)> {+ let mut stream = UnixStream::connect(socket)?;+ #[cfg(target_os = "linux")]+ let peer = {+ use std::os::fd::AsRawFd;+ let mut credentials: libc::ucred = unsafe { std::mem::zeroed() };+ let mut size = std::mem::size_of::<libc::ucred>() as libc::socklen_t;+ if unsafe {+ libc::getsockopt(+ stream.as_raw_fd(),+ libc::SOL_SOCKET,+ libc::SO_PEERCRED,+ (&mut credentials as *mut libc::ucred).cast(),+ &mut size,+ )+ } != 0+ {+ return Err(std::io::Error::last_os_error());+ }+ Some(credentials.pid as u32)+ };+ #[cfg(not(target_os = "linux"))]+ let peer = None;+ stream.set_read_timeout(Some(Duration::from_millis(300)))?;+ stream.set_write_timeout(Some(Duration::from_millis(300)))?;+ stream.write_all(+ b"GET /_ping HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n",+ )?;+ let mut response = String::new();+ stream.take(4096).read_to_string(&mut response)?;+ Ok((response, peer))+ };+ let (response, peer) = probe().map_err(|error| format!("{}: {error}", socket.display()))?;+ if response.starts_with("HTTP/1.1 200 ") || response.starts_with("HTTP/1.0 200 ") {+ Ok(peer)+ } else {+ Err(format!(+ "{}: Podman API ping failed: {response}",+ socket.display()+ ))+ }+ }++ impl Service {+ #[cfg(target_os = "linux")]+ pub fn ensure(&mut self, address: &super::Address, root: &Path) -> Result<(), Problem> {+ if !matches!(address.selector, Some(super::RuntimeSelector::PodmanLocal)) {+ return Ok(());+ }+ let runtime = std::env::var_os("XDG_RUNTIME_DIR")+ .map(PathBuf::from)+ .unwrap_or_else(|| {+ PathBuf::from(format!("/run/user/{}", unsafe { libc::getuid() }))+ });+ let socket = runtime.join("podman/podman.sock");+ let log = root.join("logs/podman-api.log");+ self.ensure_with(&socket, &log, || {+ let mut command = address.command();+ command+ .args(["system", "service", "--time=0"])+ .arg(format!("unix://{}", socket.display()));+ command+ })+ }++ pub(super) fn ensure_with(+ &mut self,+ socket: &Path,+ log: &Path,+ spawn: impl FnOnce() -> Command,+ ) -> Result<(), Problem> {+ if let Some(child) = self.child.as_mut() {+ if let Some(status) = child+ .try_wait()+ .map_err(|error| problem(error.to_string()))?+ {+ self.stop()?;+ return Err(problem(format!(+ "The owned Podman API exited with {status}. Log: {}",+ log.display()+ )));+ }+ }+ match std::fs::symlink_metadata(socket) {+ Ok(_) => return ping(socket).map(|_| ()).map_err(problem),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}+ Err(error) => return Err(problem(format!("{}: {error}", socket.display()))),+ }+ if self.child.is_some() {+ return Err(problem("The owned Podman API lost its socket."));+ }+ for directory in [socket.parent(), log.parent()].into_iter().flatten() {+ std::fs::DirBuilder::new()+ .recursive(true)+ .mode(0o700)+ .create(directory)+ .map_err(|error| problem(format!("{}: {error}", directory.display())))?;+ }+ let output = std::fs::File::create(log)+ .map_err(|error| problem(format!("{}: {error}", log.display())))?;+ let error_output = output+ .try_clone()+ .map_err(|error| problem(error.to_string()))?;+ self.child = Some(+ spawn()+ .process_group(0)+ .stdin(Stdio::null())+ .stdout(output)+ .stderr(error_output)+ .spawn()+ .map_err(|error| problem(format!("could not start Podman API: {error}")))?,+ );+ let until = Instant::now() + Duration::from_secs(10);+ let failure = loop {+ match self.child.as_mut().unwrap().try_wait() {+ Ok(Some(status)) => break format!("Podman API exited with {status}"),+ Err(error) => break format!("could not observe Podman API: {error}"),+ Ok(None) => {}+ }+ match ping(socket) {+ Ok(peer) => {+ let child = self.child.as_ref().unwrap().id();+ if peer+ .is_some_and(|pid| unsafe { libc::getpgid(pid as i32) } != child as i32)+ {+ // Another service won the bind race. Retire ours without claiming its socket.+ self.stop()?;+ return ping(socket).map(|_| ()).map_err(problem);+ }+ match std::fs::symlink_metadata(socket) {+ Ok(metadata) => {+ self.socket =+ Some((socket.to_path_buf(), metadata.dev(), metadata.ino()))+ }+ Err(error) => break format!("{}: {error}", socket.display()),+ }+ return Ok(());+ }+ Err(error) if Instant::now() >= until => break error,+ Err(_) => std::thread::sleep(Duration::from_millis(50)),+ }+ };+ let diagnostic = match std::fs::read_to_string(log) {+ Ok(contents) => contents,+ Err(error) => format!("could not read {}: {error}", log.display()),+ };+ let cleanup = self.stop();+ Err(problem(match cleanup {+ Ok(()) => format!("{failure}\n{diagnostic}"),+ Err(cleanup) => format!(+ "{failure}\n{diagnostic}\nCleanup: {} {:?}",+ cleanup.said, cleanup.detail+ ),+ }))+ }++ pub fn stop(&mut self) -> Result<(), Problem> {+ if let Some(child) = self.child.as_mut() {+ if child+ .try_wait()+ .map_err(|error| problem(error.to_string()))?+ .is_none()+ {+ // Terminate the exact held child, never a PID read from a previous session.+ if unsafe { libc::kill(-(child.id() as i32), libc::SIGTERM) } != 0 {+ let error = std::io::Error::last_os_error();+ if error.raw_os_error() != Some(libc::ESRCH) {+ return Err(problem(format!("could not stop Podman API: {error}")));+ }+ }+ let until = Instant::now() + Duration::from_secs(2);+ while child+ .try_wait()+ .map_err(|error| problem(error.to_string()))?+ .is_none()+ {+ if Instant::now() >= until {+ if unsafe { libc::kill(-(child.id() as i32), libc::SIGKILL) } != 0 {+ let error = std::io::Error::last_os_error();+ if error.raw_os_error() != Some(libc::ESRCH) {+ return Err(problem(error.to_string()));+ }+ }+ break;+ }+ std::thread::sleep(Duration::from_millis(20));+ }+ }+ child.wait().map_err(|error| problem(error.to_string()))?;+ self.child = None;+ }+ if let Some((socket, device, inode)) = &self.socket {+ match std::fs::symlink_metadata(socket) {+ Ok(metadata) if metadata.dev() == *device && metadata.ino() == *inode => {+ std::fs::remove_file(socket)+ .map_err(|error| problem(format!("{}: {error}", socket.display())))?;+ }+ Ok(_) => {} // A replacement socket is not ours.+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}+ Err(error) => return Err(problem(error.to_string())),+ }+ self.socket = None;+ }+ Ok(())+ }++ #[cfg(test)]+ pub(super) fn child_id(&self) -> Option<u32> {+ self.child.as_ref().map(Child::id)+ }+ }++ impl Drop for Service {+ fn drop(&mut self) {+ if let Err(error) = self.stop() {+ eprintln!(+ "[podman-api] cleanup failed: {} {:?}",+ error.said, error.detail+ );+ }+ }+ }+}++#[cfg(all(test, unix))]+mod local_api_tests {+ use super::local_api::Service;+ use crate::test_support::temp_root;+ use std::path::Path;+ use std::process::Command;++ fn fixture(socket: &Path) -> Command {+ let mut command = Command::new(std::env::current_exe().unwrap());+ command+ .args([+ "--exact",+ "engine::local_api_tests::api_fixture_child",+ "--nocapture",+ ])+ .env("OPENBOT_API_FIXTURE_SOCKET", socket);+ command+ }++ #[test]+ fn api_fixture_child() {+ let Some(socket) = std::env::var_os("OPENBOT_API_FIXTURE_SOCKET") else {+ return;+ };+ use std::io::{Read, Write};+ let listener = std::os::unix::net::UnixListener::bind(socket).unwrap();+ for stream in listener.incoming() {+ let mut stream = stream.unwrap();+ let mut request = Vec::new();+ while !request.ends_with(b"\r\n\r\n") {+ let mut byte = [0; 1];+ stream.read_exact(&mut byte).unwrap();+ request.push(byte[0]);+ assert!(request.len() < 4096, "fixture request must be bounded");+ }+ stream+ .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nOK")+ .unwrap();+ }+ }++ #[test]+ fn linux_api_starts_a_real_socket_and_reaps_only_its_own_child() {+ let root = temp_root("linux-api");+ std::fs::create_dir_all(&root).unwrap();+ let socket = root.join("api.sock");+ let log = root.join("api.log");+ let mut owned = Service::default();+ owned+ .ensure_with(&socket, &log, || fixture(&socket))+ .unwrap();+ let pid = owned.child_id().expect("new service is owned");+ assert_eq!(unsafe { libc::kill(pid as i32, 0) }, 0);+ let mut borrowed = Service::default();+ borrowed+ .ensure_with(&socket, &log, || panic!("reuse the existing API"))+ .unwrap();+ borrowed.stop().unwrap();+ assert_eq!(+ unsafe { libc::kill(pid as i32, 0) },+ 0,+ "unowned service must remain alive"+ );+ owned.stop().unwrap();+ assert_eq!(+ unsafe { libc::kill(pid as i32, 0) },+ -1,+ "owned child must be reaped"+ );+ assert!(+ !socket.exists(),+ "owned socket must not prevent a later start"+ );+ owned+ .ensure_with(&socket, &log, || fixture(&socket))+ .unwrap();+ owned.stop().unwrap();+ std::fs::remove_dir_all(root).unwrap();+ }++ #[test]+ fn linux_api_drop_reaps_the_owned_service_without_removing_a_replacement_socket() {+ let root = temp_root("linux-api-drop");+ std::fs::create_dir_all(&root).unwrap();+ let socket = root.join("api.sock");+ let mut service = Service::default();+ service+ .ensure_with(&socket, &root.join("api.log"), || fixture(&socket))+ .unwrap();+ let pid = service.child_id().unwrap();+ std::fs::remove_file(&socket).unwrap();+ let replacement = std::os::unix::net::UnixListener::bind(&socket).unwrap();+ drop(service);+ assert_eq!(unsafe { libc::kill(pid as i32, 0) }, -1);+ assert!(socket.exists(), "replaced socket belongs to another owner");+ drop(replacement);+ std::fs::remove_dir_all(root).unwrap();+ }++ #[test]+ fn linux_api_start_failure_preserves_diagnostics_and_reaps_child() {+ let root = temp_root("linux-api-failed");+ std::fs::create_dir_all(&root).unwrap();+ let mut service = Service::default();+ let problem = service+ .ensure_with(&root.join("api.sock"), &root.join("api.log"), || {+ let mut command = Command::new("/bin/sh");+ command.args(["-c", "echo native-service-failed >&2; exit 19"]);+ command+ })+ .unwrap_err();+ assert!(problem.detail.unwrap().contains("native-service-failed"));+ assert!(service.child_id().is_none());+ std::fs::remove_dir_all(root).unwrap();+ }++ #[test]+ fn linux_api_refuses_an_unresponsive_existing_socket_without_replacing_it() {+ let root = temp_root("linux-api-existing");+ std::fs::create_dir_all(&root).unwrap();+ let socket = root.join("api.sock");+ let listener = std::os::unix::net::UnixListener::bind(&socket).unwrap();+ let mut service = Service::default();+ assert!(service+ .ensure_with(&socket, &root.join("api.log"), || panic!(+ "must not replace existing socket"+ ))+ .is_err());+ assert!(socket.exists());+ drop(listener);+ std::fs::remove_dir_all(root).unwrap();+ }+}diff --git a/desktop/src-tauri/src/install.rs b/desktop/src-tauri/src/install.rsindex c3f46def..75a1a5fa 100644--- a/desktop/src-tauri/src/install.rs+++ b/desktop/src-tauri/src/install.rs@@ -204,7 +204,7 @@ fn digest_of(bytes: &[u8]) -> String {.collect()}-/// A fresh Mac or Windows account has no developer tools. Acquire the host runtime as that user,+/// A fresh account has no developer tools. Acquire the host runtime as that user,/// without changing PATH or requiring an administrator. Existing installations remain usable.pub fn ensure_bun(cache: &Path, existing: Option<PathBuf>) -> Result<PathBuf, Problem> {ensure_bun_with(existing, || install_bun(cache))@@ -220,7 +220,6 @@ fn ensure_bun_with(}}-#[cfg(any(windows, target_os = "macos", test))]fn bun_download(os: &str, arch: &str) -> Result<Download, Problem> {// Official bun-v1.3.14/SHASUMS256.txt. The baseline x64 build also supports older CPUs.let (file, sha256) = match (os, arch) {@@ -240,6 +239,14 @@ fn bun_download(os: &str, arch: &str) -> Result<Download, Problem> {"bun-darwin-aarch64.zip","d8b96221828ad6f97ac7ac0ab7e95872341af763001e8803e8267652c2652620",),+ ("linux", "x86_64") => (+ "bun-linux-x64-baseline.zip",+ "a063908ae08b7852ca10939bbdc6ceed3ddabce8fb9402dce83d65d73b36e6c7",+ ),+ ("linux", "aarch64") => (+ "bun-linux-aarch64.zip",+ "a27ffb63a8310375836e0d6f668ae17fa8d8d18b88c37c821c65331973a19a3b",+ ),_ => {return Err(Problem::with("OpenBot cannot install its app runtime on this kind of computer.",@@ -254,7 +261,6 @@ fn bun_download(os: &str, arch: &str) -> Result<Download, Problem> {})}-#[cfg(any(windows, target_os = "macos"))]fn install_bun(cache: &Path) -> Result<PathBuf, Problem> {let download = bun_download(std::env::consts::OS, std::env::consts::ARCH)?;let entry = format!(@@ -271,14 +277,6 @@ fn install_bun(cache: &Path) -> Result<PathBuf, Problem> {)}-#[cfg(not(any(windows, target_os = "macos")))]-fn install_bun(_cache: &Path) -> Result<PathBuf, Problem> {- Err(Problem::plain(- "bun was not found, so the API server cannot be started",- ))-}--#[cfg(any(windows, target_os = "macos", test))]fn install_bun_with(into: &Path,download: &Download,@@ -292,88 +290,54 @@ fn install_bun_with(}let archive = fetch_verified(download, into)?;let staged = into.join(format!("bun.download{}", std::env::consts::EXE_SUFFIX));- extract(&archive, &staged)?;- verify(&staged)?;- std::fs::rename(&staged, &binary).map_err(|error| unwritable(&binary, &error.to_string()))?;+ let result = extract(&archive, &staged)+ .and_then(|()| verify(&staged))+ .and_then(|()| {+ std::fs::rename(&staged, &binary)+ .map_err(|error| unwritable(&binary, &error.to_string()))+ });+ if let Err(mut problem) = result {+ if let Err(error) = std::fs::remove_file(&staged) {+ if error.kind() != std::io::ErrorKind::NotFound {+ problem.detail = Some(format!(+ "{}; could not remove incomplete runtime {}: {error}",+ problem.detail.as_deref().unwrap_or(&problem.said),+ staged.display(),+ ));+ }+ }+ return Err(problem);+ }Ok(binary)}-#[cfg(windows)]fn extract_bun(archive: &Path, target: &Path, entry: &str) -> Result<(), Problem> {- // Extract only the expected executable. Paths travel as environment values, never as- // PowerShell source, so spaces and quotes in a profile directory cannot change the command.- let script = r#"$ErrorActionPreference = 'Stop'-Add-Type -AssemblyName System.IO.Compression.FileSystem-$zip = [IO.Compression.ZipFile]::OpenRead($env:OPENBOT_BUN_ARCHIVE)-try {- $entry = $zip.GetEntry($env:OPENBOT_BUN_ENTRY)- if ($null -eq $entry) { throw 'The Bun archive does not contain the expected executable.' }- [IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $env:OPENBOT_BUN_TARGET, $true)-} finally {- $zip.Dispose()-}"#;- let output = crate::quiet::command("powershell")- .args(["-NoProfile", "-NonInteractive", "-Command", script])- .env("OPENBOT_BUN_ARCHIVE", archive)- .env("OPENBOT_BUN_TARGET", target)- .env("OPENBOT_BUN_ENTRY", entry)- .output()- .map_err(|error| {- Problem::with(- "OpenBot could not unpack its app runtime. Try again.",- error.to_string(),- )- })?;- if !output.status.success() {- return Err(Problem::with(+ let unpack_error = |error: &dyn std::fmt::Display| {+ Problem::with("OpenBot could not unpack its app runtime. Try again.",- format!(- "PowerShell {}: {}{}",- output.status,- String::from_utf8_lossy(&output.stdout),- String::from_utf8_lossy(&output.stderr)- ),- ));- }- Ok(())-}--#[cfg(target_os = "macos")]-fn extract_bun(archive: &Path, target: &Path, entry: &str) -> Result<(), Problem> {- use std::os::unix::fs::PermissionsExt;+ format!("{} entry {entry}: {error}", archive.display()),+ )+ };- // unzip ships with macOS itself. Use its absolute path and extract only the expected file;- // neither Xcode's command-line tools, Homebrew, nor a configured shell PATH is needed.- let file =+ // Only the named executable is copied to our chosen staging path. Archive paths never+ // choose output locations, and installation needs no external archive utility or shell.+ let file = std::fs::File::open(archive).map_err(|error| unpack_error(&error))?;+ let mut zip = zip::ZipArchive::new(file).map_err(|error| unpack_error(&error))?;+ let mut executable = zip.by_name(entry).map_err(|error| unpack_error(&error))?;+ let mut file =std::fs::File::create(target).map_err(|error| unwritable(target, &error.to_string()))?;- let output = crate::quiet::command("/usr/bin/unzip")- .arg("-p")- .arg(archive)- .arg(entry)- .stdout(file)- .output()- .map_err(|error| {- Problem::with(- "OpenBot could not unpack its app runtime. Try again.",- error.to_string(),- )- })?;- if !output.status.success() {- return Err(Problem::with(- "OpenBot could not unpack its app runtime. Try again.",- format!(- "unzip {}: {}",- output.status,- String::from_utf8_lossy(&output.stderr)- ),- ));+ std::io::copy(&mut executable, &mut file).map_err(|error| unpack_error(&error))?;+ drop(file);++ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(target, std::fs::Permissions::from_mode(0o755))+ .map_err(|error| unwritable(target, &error.to_string()))?;}- std::fs::set_permissions(target, std::fs::Permissions::from_mode(0o755))- .map_err(|error| unwritable(target, &error.to_string()))?;Ok(())}-#[cfg(any(windows, target_os = "macos"))]fn verify_bun(binary: &Path) -> Result<(), Problem> {let output = crate::quiet::command(binary).arg("--version")@@ -780,6 +744,8 @@ mod tests {bun_download("windows", "aarch64"),bun_download("macos", "x86_64"),bun_download("macos", "aarch64"),+ bun_download("linux", "x86_64"),+ bun_download("linux", "aarch64"),].into_iter().flatten()@@ -855,26 +821,51 @@ mod tests {(dir, download)}- #[cfg(target_os = "macos")]- fn macos_bun_zip_fixture(name: &str) -> (PathBuf, Download) {+ fn bun_zip_fixture(name: &str) -> (PathBuf, Download) {use base64::Engine as _;- // A real ZIP containing only bun-fixture/bun: a /bin/sh script printing 1.3.14.- // Fixed bytes keep both digest verification and extraction in this offline regression.+ // A deflated ZIP containing bun-fixture/bun, a /bin/sh script printing 1.3.14,+ // and an unrelated traversal entry that must never be extracted. Fixed bytes keep+ // digest verification and real decompression in this offline regression.let bytes = base64::engine::general_purpose::STANDARD.decode(- "UEsDBBQAAAAAAAAAIVwlsF+1HAAAABwAAAAPAAAAYnVuLWZpeHR1cmUvYnVuIyEvYmluL3NoCnByaW50ZiAnMS4zLjE0XG4nClBLAQIUAxQAAAAAAAAAIVwlsF+1HAAAABwAAAAPAAAAAAAAAAAAAACAAQAAAABidW4tZml4dHVyZS9idW5QSwUGAAAAAAEAAQA9AAAASQAAAAAA",+ "UEsDBBQAAAAIAAAAIVwlsF+1HgAAABwAAAAPAAAAYnVuLWZpeHR1cmUvYnVuU1bUT8rM0y/O4CooyswrSVNQN9Qz1jM0iclT5wIAUEsDBBQAAAAIAAAAIVw6VdAHFwAAABUAAAANAAAALi4vdW5leHBlY3RlZMstLS5RyMsvUUhKVUitKClKTC5JTQEAUEsBAhQDFAAAAAgAAAAhXCWwX7UeAAAAHAAAAA8AAAAAAAAAAAAAAIABAAAAAGJ1bi1maXh0dXJlL2J1blBLAQIUAxQAAAAIAAAAIVw6VdAHFwAAABUAAAANAAAAAAAAAAAAAACAAUsAAAAuLi91bmV4cGVjdGVkUEsFBgAAAAACAAIAeAAAAI0AAAAAAA==",).unwrap();let root = temp_root(name);std::fs::create_dir_all(&root).unwrap();let download = Download {url: "http://127.0.0.1:1/never-reached".into(),- sha256: "15be25bd806770f73afe7d2bab41ae26b2a380645e3100c60f391dc97ac0126e",+ sha256: "afeced1e41e23b9a5a7c63fb917f68ee663a3735f02fe717cf859be06b1e29b6",file: "bun-fixture.zip",};std::fs::write(root.join(download.file), bytes).unwrap();(root, download)}+ #[test]+ fn linux_runtime_downloads_are_pinned_for_both_supported_architectures() {+ for (arch, file, sha256) in [+ (+ "x86_64",+ "bun-linux-x64-baseline.zip",+ "a063908ae08b7852ca10939bbdc6ceed3ddabce8fb9402dce83d65d73b36e6c7",+ ),+ (+ "aarch64",+ "bun-linux-aarch64.zip",+ "a27ffb63a8310375836e0d6f668ae17fa8d8d18b88c37c821c65331973a19a3b",+ ),+ ] {+ let download = bun_download("linux", arch).unwrap();+ assert_eq!(download.file, file);+ assert_eq!(download.sha256, sha256);+ assert_eq!(+ download.url,+ format!("https://github.com/oven-sh/bun/releases/download/bun-v{BUN}/{file}")+ );+ }+ assert!(bun_download("linux", "unsupported").is_err());+ }+#[test]fn macos_runtime_downloads_are_pinned_for_both_supported_architectures() {for (arch, file) in [@@ -892,15 +883,15 @@ mod tests {}#[test]- #[cfg(target_os = "macos")]- fn macos_bun_installation_works_without_developer_tools() {+ #[cfg(unix)]+ fn bun_installation_works_without_developer_tools() {if crate::test_support::isolated_process(- "install::tests::macos_bun_installation_works_without_developer_tools",+ "install::tests::bun_installation_works_without_developer_tools",) {return;}std::env::set_var("PATH", "/openbot-no-developer-tools");- let (root, download) = macos_bun_zip_fixture("bun Mac's fresh account");+ let (root, download) = bun_zip_fixture("bun user's fresh account");let binary = ensure_bun_with(None, || {install_bun_with(&root,@@ -917,9 +908,33 @@ mod tests {}#[test]- #[cfg(target_os = "macos")]- fn macos_missing_bun_archive_entry_is_not_published_or_run() {- let (root, download) = macos_bun_zip_fixture("bun Mac missing entry");+ fn bun_extraction_only_writes_the_expected_file() {+ let (root, download) = bun_zip_fixture("bun extraction paths");+ let into = root.join("installed");+ std::fs::create_dir(&into).unwrap();+ let target = into.join(format!("bun{}", std::env::consts::EXE_SUFFIX));+ let archive = fetch_verified(&download, &root).unwrap();+ extract_bun(&archive, &target, "bun-fixture/bun").unwrap();+ assert_eq!(+ std::fs::read(&target).unwrap(),+ b"#!/bin/sh\nprintf '1.3.14\\n'\n"+ );+ assert_eq!(std::fs::read_dir(&into).unwrap().count(), 1);+ assert!(!root.join("unexpected").exists());+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ assert_eq!(+ std::fs::metadata(target).unwrap().permissions().mode() & 0o777,+ 0o755+ );+ }+ std::fs::remove_dir_all(root).unwrap();+ }++ #[test]+ fn missing_bun_archive_entry_is_not_published_or_run() {+ let (root, download) = bun_zip_fixture("bun missing entry");let failure = install_bun_with(&root,&download,@@ -927,8 +942,13 @@ mod tests {|_| panic!("a missing archive entry must not be run"),).unwrap_err();- assert!(failure.detail.unwrap().contains("unzip"));- assert!(!root.join("bun").exists());+ assert!(failure.detail.unwrap().contains("missing/bun"));+ assert!(!root+ .join(format!("bun{}", std::env::consts::EXE_SUFFIX))+ .exists());+ assert!(!root+ .join(format!("bun.download{}", std::env::consts::EXE_SUFFIX))+ .exists());std::fs::remove_dir_all(root).unwrap();}@@ -1005,13 +1025,19 @@ mod tests {let result = install_bun_with(&dir,&download,- |_, _| Err(failure.clone()),+ |_, target| {+ std::fs::write(target, b"partially extracted executable").unwrap();+ Err(failure.clone())+ },|_| panic!("failed extraction must not be executed"),);assert_eq!(result, Err(failure));assert!(!dir.join(format!("bun{}", std::env::consts::EXE_SUFFIX)).exists());+ assert!(!dir+ .join(format!("bun.download{}", std::env::consts::EXE_SUFFIX))+ .exists());let _ = std::fs::remove_dir_all(dir);}@@ -1034,6 +1060,9 @@ mod tests {assert!(!dir.join(format!("bun{}", std::env::consts::EXE_SUFFIX)).exists());+ assert!(!dir+ .join(format!("bun.download{}", std::env::consts::EXE_SUFFIX))+ .exists());let _ = std::fs::remove_dir_all(dir);}diff --git a/desktop/src-tauri/src/macos-podman-ports.yml b/desktop/src-tauri/src/macos-podman-ports.ymlnew file mode 100644index 00000000..20b0ae68--- /dev/null+++ b/desktop/src-tauri/src/macos-podman-ports.yml@@ -0,0 +1,22 @@+# Podman's macOS VM strips host IPs before configuring rootless port forwarding. Publishing+# IPv4 and IPv6 loopback for the same port therefore creates two identical internal mappings.+# !override replaces the port list; ordinary Compose merging would retain the IPv6 entries.+services:+ postgres:+ ports: !override+ - "127.0.0.1:${POSTGRES_PORT:-5432}:5432"+ supervisor:+ ports: !override+ - "127.0.0.1:${SUPERVISOR_PORT:-4500}:4300"+ agent-computer:+ ports: !override+ - "127.0.0.1:${COMPUTER_PORT:-4100}:4100"+ agent-bot:+ ports: !override+ - "127.0.0.1:${BOT_PORT:-4200}:4200"+ agent-langgraph:+ ports: !override+ - "127.0.0.1:${LANGGRAPH_PORT:-4201}:4201"+ agent-harness:+ ports: !override+ - "127.0.0.1:${PICKED_HARNESS_PORT:-4202}:${PICKED_HARNESS_PORT:-4202}"diff --git a/desktop/src-tauri/src/main.rs b/desktop/src-tauri/src/main.rsindex f7c6bbf8..fcb7c2c5 100644--- a/desktop/src-tauri/src/main.rs+++ b/desktop/src-tauri/src/main.rs@@ -29,6 +29,9 @@ struct Shell {host_access: Mutex<Option<host_access::HostAccess>>,/// Named, because a restart policy that cannot say which process died cannot start it again.children: Mutex<Vec<(&'static str, std::process::Child)>>,+ /// Native Linux engine API owned by this desktop session, kept through Stop/Start.+ #[cfg(target_os = "linux")]+ podman_api: Mutex<engine::local_api::Service>,/// Which run is the current one.////// Stopping and starting again inside two seconds would otherwise leave the previous watcher@@ -229,26 +232,32 @@ struct ReadyRespondingEngine {/// Return a responding engine only after Compose is present too.fn ready_responding_engine_after_compose_repair(found: engine::EngineStatus,+ install_missing_native: bool,mut install_engine: impl FnMut() -> Result<String, Problem>,mut detect: impl FnMut() -> engine::EngineStatus,mut composes: impl FnMut(&engine::Address) -> bool,) -> Result<Option<ReadyRespondingEngine>, Problem> {- let Some(address) = found.address.clone().filter(|_| found.responding) else {+ if let Some(address) = found.address.clone().filter(|_| found.responding) {+ if composes(&address) {+ return Ok(Some(ReadyRespondingEngine {+ address,+ detail: found.detail,+ installed: None,+ }));+ }+ } else if !install_missing_native {return Ok(None);- };- if composes(&address) {- return Ok(Some(ReadyRespondingEngine {- address,- detail: found.detail,- installed: None,- }));}let installed = install_engine()?;let ready = detect();let Some(address) = ready.address.clone().filter(|_| ready.responding) else {return Err(Problem::with(- "OpenBot installed Compose, but the container engine is not answering. Try again.",+ if install_missing_native {+ "OpenBot installed the container software, but the engine is not answering. Try again."+ } else {+ "OpenBot installed Compose, but the container engine is not answering. Try again."+ },ready.detail,));};@@ -489,6 +498,7 @@ async fn engine_ready(app: &tauri::AppHandle) -> Result<engine::Address, Problemlet existing = tauri::async_runtime::spawn_blocking(move || {ready_responding_engine_after_compose_repair(found,+ cfg!(target_os = "linux"),|| install::install_engine(&root),engine::detect,engine::Address::composes,@@ -506,6 +516,23 @@ async fn engine_ready(app: &tauri::AppHandle) -> Result<engine::Address, Problemif let Some(installed) = ready.installed {report(app, "install-engine", true, installed);}+ #[cfg(target_os = "linux")]+ {+ let handle = app.clone();+ let address = ready.address.clone();+ tauri::async_runtime::spawn_blocking(move || {+ let shell = handle.state::<Shell>();+ let _startup = shell.startup.lock().unwrap();+ ensure_linux_podman_api(&shell, &address)+ })+ .await+ .map_err(|error| {+ Problem::with(+ "OpenBot could not start its container service.",+ error.to_string(),+ )+ })??;+ }report(app, "engine", true, ready.detail);return Ok(ready.address);}@@ -596,6 +623,21 @@ async fn engine_ready(app: &tauri::AppHandle) -> Result<engine::Address, Problem})}+/// Called while holding startup so Quit cannot retire the service during its acquisition.+#[cfg(target_os = "linux")]+fn ensure_linux_podman_api(shell: &Shell, address: &engine::Address) -> Result<(), Problem> {+ if !matches!(*shell.quit.phase.lock().unwrap(), QuitPhase::Idle) {+ return Err(Problem::plain(+ "OpenBot is quitting. Start it again to continue.",+ ));+ }+ shell+ .podman_api+ .lock()+ .unwrap()+ .ensure(&address.pin()?, &stack::default_root())+}+/// Install the latest published deployment on first use, then keep its recorded version.////// Local preparation fetches the manifest needed by both launch and plan sign-in images.@@ -989,6 +1031,10 @@ async fn start_stack_inner<R: tauri::Runtime>(return Err(status.detail.into());};let found = found.pin()?;+ #[cfg(target_os = "linux")]+ ensure_linux_podman_api(&shell, &found)?;+ #[cfg(target_os = "linux")]+ let status = found.status();acquire::prepare_for_compose(&found)?;let bun = preparation::require(&root, Some(&requested_harness), &found)?;@@ -1857,6 +1903,13 @@ whereif let Err(problem) = down_containers_with(shell, &root, down) {failures.push(format!("Compose down failed: {problem}"));}+ #[cfg(target_os = "linux")]+ if let Err(problem) = shell.podman_api.lock().unwrap().stop() {+ failures.push(format!(+ "Container API cleanup failed: {}",+ problem_detail(problem)+ ));+ }if failures.is_empty() {clear_recovery_required(shell, &root);}@@ -2452,8 +2505,16 @@ async fn begin_claude_sign_in(app: tauri::AppHandle, root: String) -> Result<Str* carry Anthropic's bundled CLI, which is what does the OAuth. Letting the screen name an image* would make the sign-in depend on a choice that has nothing to do with it.*/+ #[cfg(target_os = "linux")]+ let service_app = app.clone();let (signing, url) = tauri::async_runtime::spawn_blocking(move || {let (address, image) = prepared_sign_in(&root, openbot_desktop_lib::plan::SIGN_IN_IMAGE)?;+ #[cfg(target_os = "linux")]+ {+ let shell = service_app.state::<Shell>();+ let _startup = shell.startup.lock().unwrap();+ ensure_linux_podman_api(&shell, &address)?;+ }openbot_desktop_lib::plan::SigningIn::begin(&address, &image).map_err(Problem::from)}).await@@ -2506,9 +2567,17 @@ async fn begin_chatgpt_sign_in() -> Result<String, openbot_desktop_lib::problem::Problem> {let root = stack::root_from(&root);remember_selected_root(&app.state::<Shell>(), &root);+ #[cfg(target_os = "linux")]+ let service_app = app.clone();let (signing, url) = tauri::async_runtime::spawn_blocking(move || {let (address, image) =prepared_sign_in(&root, openbot_desktop_lib::plan::CHATGPT_SIGN_IN_IMAGE)?;+ #[cfg(target_os = "linux")]+ {+ let shell = service_app.state::<Shell>();+ let _startup = shell.startup.lock().unwrap();+ ensure_linux_podman_api(&shell, &address)?;+ }openbot_desktop_lib::plan::SigningInToChatGpt::begin(&address, &image)}).await@@ -4377,6 +4446,71 @@ mod tests {}}+ #[test]+ fn linux_first_install_redetects_native_podman_without_a_virtual_machine() {+ let missing = engine::EngineStatus {+ engine: None,+ address: None,+ responding: false,+ engine_socket: None,+ detail: "No container engine yet.".into(),+ };+ let trace = std::cell::RefCell::new(Vec::new());+ let ready = ready_responding_engine_after_compose_repair(+ missing,+ true,+ || {+ trace.borrow_mut().push("install");+ Ok("Podman and Compose installed".into())+ },+ || {+ trace.borrow_mut().push("detect");+ engine::EngineStatus {+ engine: Some(engine::Engine::Podman),+ address: Some(engine::Address::new(engine::Engine::Podman, None)),+ responding: true,+ engine_socket: None,+ detail: "native Podman answers".into(),+ }+ },+ |_| {+ trace.borrow_mut().push("compose");+ true+ },+ )+ .unwrap()+ .expect("Linux must return its newly installed native engine, not request a VM");+ assert_eq!(ready.address.engine, engine::Engine::Podman);+ assert!(ready.address.connection.is_none());+ assert_eq!(*trace.borrow(), ["install", "detect", "compose"]);+ }++ #[test]+ fn linux_failed_native_engine_is_an_error_instead_of_a_request_for_qemu() {+ let stopped = engine::EngineStatus {+ engine: Some(engine::Engine::Podman),+ address: None,+ responding: false,+ engine_socket: None,+ detail: "podman native operation failed".into(),+ };+ let result = ready_responding_engine_after_compose_repair(+ stopped.clone(),+ true,+ || Ok("installed".into()),+ || stopped.clone(),+ |_| panic!("a failed engine cannot run Compose"),+ );+ assert!(+ result.is_err(),+ "Ok(None) would enter the virtual-machine path"+ );+ assert_eq!(+ result.err().unwrap().detail.as_deref(),+ Some("podman native operation failed")+ );+ }+#[test]fn responding_engine_without_compose_installs_then_redetects_before_returning() {let before = engine::EngineStatus {@@ -4401,6 +4535,7 @@ mod tests {let ready = ready_responding_engine_after_compose_repair(before,+ false,|| {trace.borrow_mut().push("install-engine".to_string());Ok("Compose installed.".into())@@ -4447,6 +4582,7 @@ mod tests {engine_socket: None,detail: "podman is answering.".into(),},+ false,|| {path.write_binary(install::compose_provider_name(), "compose-provider");installed = true;@@ -4767,13 +4903,20 @@ mod tests {path: SerializedPath,app: tauri::App<tauri::test::MockRuntime>,window: tauri::WebviewWindow<tauri::test::MockRuntime>,+ previous_runtime: Option<std::ffi::OsString>,}impl Fixture {fn new() -> Self {- let base = temp_root("container-root-workflow");+ // Unix socket paths must remain below sockaddr_un's length limit on macOS too.+ let base = PathBuf::from("/tmp")+ .join(temp_root("container-root-workflow").file_name().unwrap());std::fs::create_dir_all(&base).unwrap();let base = base.canonicalize().unwrap();+ let runtime = base.join("runtime");+ std::fs::create_dir_all(&runtime).unwrap();+ let previous_runtime = std::env::var_os("XDG_RUNTIME_DIR");+ std::env::set_var("XDG_RUNTIME_DIR", &runtime);let a = base.join("a");let b = base.join("b");write_installed_deployment(&a);@@ -4807,9 +4950,45 @@ fn main() {writeln!(trace,"{}\t{}",identity,original.join(" ")).unwrap();let mut log=fs::OpenOptions::new().create(true).append(true).open(&record).unwrap();writeln!(log,"{}\t{}",cwd.display(),args.join(" ")).unwrap();+ // Mac Podman adds its port overlay only to service-creating commands. Keep the original+ // arguments in the ownership trace, then dispatch the same fixture behavior for up/run.+ if engine=="podman" && args.iter().any(|arg| arg=="up" || arg=="run") {+ while args.get(1).is_some_and(|arg| arg=="-f") {+ assert!(std::path::Path::new(&args[2]).is_file());+ args.drain(1..3);+ }+ }let words:Vec<&str>=args.iter().map(String::as_str).collect();if words==["context","show"] { println!("{target}"); return; }if words.starts_with(&["context","inspect"]) { println!("unix:///owned-default.sock"); return; }+ if words.starts_with(&["system", "service"]) {+ use std::{io::Read, os::unix::net::UnixListener, time::{Duration, Instant}};+ assert_eq!(engine, "podman");+ assert_eq!(target, "local");+ let socket=PathBuf::from(words.last().unwrap().strip_prefix("unix://").unwrap());+ assert_eq!(socket, PathBuf::from(env::var_os("XDG_RUNTIME_DIR").unwrap()).join("podman/podman.sock"));+ let listener=UnixListener::bind(&socket).unwrap();+ listener.set_nonblocking(true).unwrap();+ let deadline=Instant::now()+Duration::from_secs(60);+ while Instant::now()<deadline {+ match listener.accept() {+ Ok((mut stream,_)) => {+ stream.set_read_timeout(Some(Duration::from_secs(1))).unwrap();+ stream.set_write_timeout(Some(Duration::from_secs(1))).unwrap();+ let mut request=Vec::new();+ while !request.ends_with(b"\r\n\r\n") {+ let mut byte=[0;1]; stream.read_exact(&mut byte).unwrap(); request.push(byte[0]);+ assert!(request.len()<4096);+ }+ assert!(request.starts_with(b"GET /_ping HTTP/1.1\r\n"));+ stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nOK").unwrap();+ }+ Err(error) if error.kind()==std::io::ErrorKind::WouldBlock => std::thread::sleep(Duration::from_millis(10)),+ Err(error) => panic!("fixture API accept failed: {error}"),+ }+ }+ return;+ }if words.first()==Some(&"system") { println!("{target}"); return; }if words.first()==Some(&"machine") { println!("[]"); return; }if !base.join(format!("{engine}-ready")).exists() { eprintln!("synthetic original runtime unavailable"); std::process::exit(74); }@@ -4818,6 +4997,7 @@ fn main() {["version","--format",_] => println!("1.44"),["info","--format","{{.Host.ServiceIsRemote}}"] => println!("false"),["compose","version"] => println!("Synthetic Compose"),+ ["compose","config","--environment"] => (),["compose","ps","--format",_] => (),["compose","up",..] => {fs::write(cwd.join("fixture-containers-running"),&identity).unwrap();@@ -4870,6 +5050,7 @@ fn main() {path,app,window,+ previous_runtime,}}@@ -4980,6 +5161,18 @@ fn main() {impl Drop for Fixture {fn drop(&mut self) {+ #[cfg(target_os = "linux")]+ self.app+ .state::<Shell>()+ .podman_api+ .lock()+ .unwrap()+ .stop()+ .expect("stop owned fixture API before deleting its runtime directory");+ match &self.previous_runtime {+ Some(runtime) => std::env::set_var("XDG_RUNTIME_DIR", runtime),+ None => std::env::remove_var("XDG_RUNTIME_DIR"),+ }println!("CONTAINER_CLEANUP={}",serde_json::json!({"base":self.base,"bin":self.path.bin(),"commands":self.commands(),"affinity":std::fs::read_to_string(self.base.join("affinity.log")).unwrap_or_default(),"engineBinarySha256":format!("{:x}",Sha256::digest(std::fs::read(self.path.bin().join("docker")).unwrap())),"persistentFixtureProcesses":0})@@ -5190,6 +5383,44 @@ fn main() {.is_none());}+ #[test]+ fn local_podman_fixture_serves_api_on_its_private_runtime_socket() {+ if crate::test_support::isolated_process("tests::container_root::local_podman_fixture_serves_api_on_its_private_runtime_socket") { return; }+ use std::io::{Read, Write};+ let fixture = Fixture::new();+ let socket = fixture.base.join("runtime/podman/podman.sock");+ std::fs::create_dir_all(socket.parent().unwrap()).unwrap();+ let mut service = engine::Address::new(engine::Engine::Podman, None)+ .command()+ .args(["--remote=false", "system", "service", "--time=0"])+ .arg(format!("unix://{}", socket.display()))+ .spawn()+ .unwrap();+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);+ let response = loop {+ match std::os::unix::net::UnixStream::connect(&socket) {+ Ok(mut stream) => {+ stream+ .set_read_timeout(Some(std::time::Duration::from_secs(1)))+ .unwrap();+ stream.write_all(b"GET /_ping HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n").unwrap();+ let mut response = String::new();+ let read = stream.read_to_string(&mut response);+ break read.map(|_| response);+ }+ Err(error) if std::time::Instant::now() >= deadline => break Err(error),+ Err(_) => std::thread::sleep(std::time::Duration::from_millis(10)),+ }+ };+ service.kill().unwrap();+ service.wait().unwrap();+ assert!(response.unwrap().starts_with("HTTP/1.1 200 OK\r\n"));+ assert_eq!(+ std::env::var_os("XDG_RUNTIME_DIR").unwrap(),+ fixture.base.join("runtime")+ );+ }+#[test]fn local_podman_fixture_keeps_linux_selector_independent_of_remote_defaults() {if crate::test_support::isolated_process("tests::container_root::local_podman_fixture_keeps_linux_selector_independent_of_remote_defaults") { return; }diff --git a/desktop/src-tauri/src/stack.rs b/desktop/src-tauri/src/stack.rsindex d8fd7131..34800df9 100644--- a/desktop/src-tauri/src/stack.rs+++ b/desktop/src-tauri/src/stack.rs@@ -179,6 +179,100 @@ fn compose_command(engine: &Address, root: &Path, secrets: &Secrets) -> Commandcommand}+const MACOS_PODMAN_PORTS_FILE: &str = ".openbot-macos-podman.yml";+const MACOS_PODMAN_PORTS: &str = include_str!("macos-podman-ports.yml");++/// Only service creation needs the Mac Podman port overlay. In particular, `run migrate` can+/// create its Postgres dependency, so it must use the same configuration as `up`.+fn compose_start_command(+ engine: &Address,+ root: &Path,+ secrets: &Secrets,+ os: &str,+) -> Result<Command, Problem> {+ let mut command = compose_command(engine, root, secrets);+ if os != "macos" || engine.engine != crate::engine::Engine::Podman {+ return Ok(command);+ }++ // Let Compose read/interpolate .env and COMPOSE_ENV_FILES itself. Adding -f directly would+ // otherwise discard both implicit override files and COMPOSE_FILE from that environment.+ // This output can contain credentials: retain only file-selection settings, never log it.+ let environment = compose_command(engine, root, secrets)+ .args(["config", "--environment"])+ .output()+ .map_err(|error| {+ Problem::with(+ "OpenBot could not read the deployment's Compose settings.",+ error.to_string(),+ )+ })?;+ if !environment.status.success() {+ return Err(Problem::with(+ "OpenBot could not read the deployment's Compose settings.",+ command_said(&environment.stderr),+ ));+ }+ let environment = String::from_utf8(environment.stdout)+ .map_err(|_| Problem::plain("Compose returned unreadable deployment settings."))?;+ let files = compose_files(root, &environment)?;+ let overlay = root.join(MACOS_PODMAN_PORTS_FILE);+ if std::fs::read(&overlay).ok().as_deref() != Some(MACOS_PODMAN_PORTS.as_bytes()) {+ std::fs::write(&overlay, MACOS_PODMAN_PORTS).map_err(|error| {+ Problem::with(+ "OpenBot could not prepare the Mac Podman port settings.",+ error.to_string(),+ )+ })?;+ }+ for file in files {+ command.arg("-f").arg(file);+ }+ command.arg("-f").arg(MACOS_PODMAN_PORTS_FILE);+ Ok(command)+}++fn compose_files(root: &Path, environment: &str) -> Result<Vec<String>, Problem> {+ let setting = |key: &str| {+ environment.lines().find_map(|line| {+ let (name, value) = line.split_once('=')?;+ (name == key).then_some(value)+ })+ };+ if let Some(files) = setting("COMPOSE_FILE") {+ let separator = setting("COMPOSE_PATH_SEPARATOR")+ .filter(|value| !value.is_empty())+ .unwrap_or(":"); // Only used on macOS.+ return Ok(files.split(separator).map(str::to_owned).collect());+ }++ // Compose-go's default discovery order. A valid installed deployment contains its base+ // file in this directory, so there is no need to search outside the selected installation.+ let first = |names: &[&str]| {+ names+ .iter()+ .find(|name| root.join(name).exists())+ .map(|name| (*name).to_owned())+ };+ let base = first(&[+ "compose.yaml",+ "compose.yml",+ "docker-compose.yml",+ "docker-compose.yaml",+ ])+ .ok_or_else(|| Problem::plain("The selected installation has no Compose file."))?;+ let mut files = vec![base];+ if let Some(existing) = first(&[+ "compose.override.yml",+ "compose.override.yaml",+ "docker-compose.override.yml",+ "docker-compose.override.yaml",+ ]) {+ files.push(existing);+ }+ Ok(files)+}+/// Resolve only image references, using public installation overrides before credentials exist.pub fn installation_images(engine: &Address,@@ -274,7 +368,7 @@ pub fn up(* `up`, because `--profile` is an option of `compose` itself and not of the subcommand.*/let requested = selected_services(harness, bots);- let mut command = compose_command(engine, root, secrets);+ let mut command = compose_start_command(engine, root, secrets, std::env::consts::OS)?;if harness {command.args(["--profile", "harness"]);}@@ -308,7 +402,7 @@ pub fn migrate() -> Result<(), crate::problem::Problem> {// The installation step supplies this image. `run` does not accept `--no-build`, and its// explicit no-pull policy must report a missing image without starting another download.- let output = compose_command(engine, root, secrets)+ let output = compose_start_command(engine, root, secrets, std::env::consts::OS)?.args(["run", "--rm", "--pull", "never", "migrate"]).output().map_err(|error| format!("could not run migrations: {error}"))?;@@ -3931,6 +4025,27 @@ fn main() {writeln!(file, "{}\t{}", cwd.display(), joined).unwrap();}let scenario = std::env::var("OPENBOT_FAKE_ENGINE_SCENARIO").unwrap();+ if scenario == "macos-podman-start" {+ let actual = if args.first().map(String::as_str) == Some("--connection") { &args[2..] } else { &args[..] };+ if actual == ["compose", "config", "--environment"] {+ if std::path::Path::new(".fixture-config-failure").exists() {+ eprintln!("synthetic invalid deployment override");+ std::process::exit(17);+ }+ print!("{}", std::fs::read_to_string(".fixture-compose-environment").unwrap_or_default());+ return;+ }+ if actual.iter().any(|arg| arg == "up" || arg == "run") {+ let files: Vec<_> = actual.windows(2).filter(|pair| pair[0] == "-f").map(|pair| &pair[1]).collect();+ if !files.iter().any(|file| file.ends_with(".openbot-macos-podman.yml")) {+ eprintln!("Error response from daemon: rootlessport conflict with ID 1");+ std::process::exit(126);+ }+ for file in files { assert!(std::path::Path::new(file).is_file(), "missing compose file {file}"); }+ return;+ }+ panic!("unexpected startup command: {actual:?}");+ }if scenario == "computer-stop" {let root = std::path::PathBuf::from(std::env::var("OPENBOT_TEST_ENGINE_RECORD").unwrap()).with_extension("");let race = root.join(".fixture-race").exists();@@ -6016,6 +6131,193 @@ fn main() {assert!(started.elapsed() < patience, "a released port kept waiting");}+ #[test]+ fn compose_port_overlay_is_limited_to_macos_podman() {+ let root = temp_root("compose-platform-policy");+ let secrets = Secrets::from([("SYNTHETIC_SETTING".into(), "preserved".into())]);+ for (engine, os) in [+ (crate::engine::Engine::Docker, "macos"),+ (crate::engine::Engine::Docker, "linux"),+ (crate::engine::Engine::Docker, "windows"),+ (crate::engine::Engine::Podman, "linux"),+ (crate::engine::Engine::Podman, "windows"),+ ] {+ let command =+ compose_start_command(&Address::new(engine, None), &root, &secrets, os).unwrap();+ assert_eq!(command.get_args().collect::<Vec<_>>(), ["compose"]);+ assert_eq!(command.get_current_dir(), Some(root.as_path()));+ assert!(command+ .get_envs()+ .any(|(key, value)| key == "SYNTHETIC_SETTING"+ && value == Some(std::ffi::OsStr::new("preserved"))));+ assert!(+ !root.exists(),+ "{engine:?} on {os} must not write a Mac Podman overlay"+ );+ }+ }++ #[test]+ fn compose_port_overlay_preserves_discovery_and_explicit_file_selection() {+ let root = temp_root("compose-file-selection");+ std::fs::create_dir_all(&root).unwrap();+ for file in ["docker-compose.yml", "docker-compose.override.yml"] {+ std::fs::write(root.join(file), "services: {}\n").unwrap();+ }+ assert_eq!(+ compose_files(&root, "").unwrap(),+ ["docker-compose.yml", "docker-compose.override.yml"]+ );+ std::fs::write(root.join("compose.yaml"), "services: {}\n").unwrap();+ std::fs::write(root.join("compose.override.yml"), "services: {}\n").unwrap();+ assert_eq!(+ compose_files(&root, "").unwrap(),+ ["compose.yaml", "compose.override.yml"]+ );+ assert_eq!(+ compose_files(&root, "COMPOSE_FILE=first.yml:folder/custom file.yml\n").unwrap(),+ ["first.yml", "folder/custom file.yml"]+ );+ assert_eq!(+ compose_files(+ &root,+ "COMPOSE_FILE=first.yml|custom.yml\nCOMPOSE_PATH_SEPARATOR=|\n"+ )+ .unwrap(),+ ["first.yml", "custom.yml"]+ );+ std::fs::remove_dir_all(root).unwrap();+ }++ /// Real Compose merging is the important assertion: without !override, IPv6 ports survive.+ /// This only reads configuration; it never contacts a container engine or registry.+ #[test]+ #[ignore = "requires Docker Compose; only reads configuration, no running engine needed"]+ fn macos_podman_port_overlay_replaces_all_six_ports_and_preserves_other_settings() {+ let root = temp_root("compose-ports-merge");+ std::fs::create_dir_all(&root).unwrap();+ let source = include_str!("../../../docker-compose.yml");+ std::fs::write(root.join("docker-compose.yml"), source).unwrap();+ std::fs::write(root.join(MACOS_PODMAN_PORTS_FILE), MACOS_PODMAN_PORTS).unwrap();+ std::fs::write(root.join("docker-compose.override.yml"), "services:\n supervisor:\n environment:\n COMPUTER_NAMESPACE: regression-kept\n labels:\n regression: kept\n").unwrap();+ let docker =+ std::env::var_os("OPENBOT_TEST_COMPOSE_DOCKER").unwrap_or_else(|| "docker".into());+ let config = |overlay: bool| {+ let mut command = Command::new(&docker);+ command+ .current_dir(&root)+ .env_clear()+ .env("PATH", env!("OPENBOT_TEST_TOOL_PATH"));+ command.arg("compose");+ if overlay {+ command.args([+ "-f",+ "docker-compose.yml",+ "-f",+ "docker-compose.override.yml",+ "-f",+ MACOS_PODMAN_PORTS_FILE,+ ]);+ }+ let output = command+ .args(["--profile", "*", "config", "--format", "json"])+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "{}",+ String::from_utf8_lossy(&output.stderr)+ );+ serde_json::from_slice::<serde_json::Value>(&output.stdout).unwrap()+ };+ for settings in [+ "PICKED_HARNESS_IMAGE=synthetic-harness:local\n".to_string(),+ "PICKED_HARNESS_IMAGE=synthetic-harness:local\nPOSTGRES_PORT=15432\nSUPERVISOR_PORT=14500\nCOMPUTER_PORT=14100\nBOT_PORT=14200\nLANGGRAPH_PORT=14201\nPICKED_HARNESS_PORT=14206\n".to_string(),+ ] {+ std::fs::write(root.join(".env"), &settings).unwrap();+ let mut before = config(false);+ let after = config(true);+ let mut published = 0;+ for (_, service) in before["services"].as_object_mut().unwrap() {+ if let Some(ports) = service.get_mut("ports").and_then(serde_json::Value::as_array_mut) {+ assert_eq!(ports.len(), 2, "the released port pattern must exercise dual loopback");+ ports.retain(|port| port["host_ip"] == "127.0.0.1");+ assert_eq!(ports.len(), 1);+ published += 1;+ }+ }+ assert_eq!(published, 6, "all published services must be covered");+ assert_eq!(after, before, "only the duplicate IPv6 loopback mappings may change");+ assert_eq!(std::fs::read_to_string(root.join(".env")).unwrap(), settings);+ assert_eq!(std::fs::read_to_string(root.join("docker-compose.yml")).unwrap(), source);+ }+ std::fs::remove_dir_all(root).unwrap();+ }++ #[cfg(target_os = "macos")]+ #[test]+ fn macos_podman_up_and_migrate_keep_deployment_overrides_without_duplicate_ports() {+ if crate::test_support::isolated_process("stack::tests::macos_podman_up_and_migrate_keep_deployment_overrides_without_duplicate_ports") { return; }+ let path = PathFixture::with_fake_engine("macos-podman-start");+ let [_, podman] = computer_stop_addresses(&path);+ let (root, record) = computer_stop_root(&path, "podman-start", "{}");+ let original = "services: {}\n";+ let settings = "POSTGRES_PORT=5544\nPICKED_HARNESS_PORT=4206\n";+ std::fs::write(root.join(".env"), settings).unwrap();+ std::fs::write(root.join("docker-compose.override.yml"), "services: {}\n").unwrap();+ let services = up(&podman, &root, true, BundledBots::none(), &Secrets::new()).unwrap();+ assert_eq!(+ services,+ ["postgres", "supervisor", "agent-computer", "agent-harness"]+ );+ migrate(&podman, &root, &Secrets::new()).unwrap();+ let log = std::fs::read_to_string(&record).unwrap();+ for action in [+ "--profile harness up -d --no-build --pull never",+ "run --rm --pull never migrate",+ ] {+ let line = log.lines().find(|line| line.contains(action)).unwrap();+ let base = line.find("-f docker-compose.yml").unwrap();+ let existing = line.find("-f docker-compose.override.yml").unwrap();+ let desktop = line.find(".openbot-macos-podman.yml").unwrap();+ assert!(base < existing && existing < desktop, "{line}");+ }+ assert_eq!(+ std::fs::read_to_string(root.join("docker-compose.yml")).unwrap(),+ original+ );+ assert_eq!(+ std::fs::read_to_string(root.join(".env")).unwrap(),+ settings+ );++ std::fs::write(root.join("custom override.yml"), "services: {}\n").unwrap();+ std::fs::write(+ root.join(".fixture-compose-environment"),+ "COMPOSE_FILE=docker-compose.yml;custom override.yml\nCOMPOSE_PATH_SEPARATOR=;\n",+ )+ .unwrap();+ std::fs::remove_file(&record).unwrap();+ migrate(&podman, &root, &Secrets::new()).unwrap();+ let log = std::fs::read_to_string(&record).unwrap();+ assert!(+ log.contains("-f docker-compose.yml -f custom override.yml"),+ "{log}"+ );+ assert!(!log.contains("docker-compose.override.yml"), "{log}");++ std::fs::write(root.join(".fixture-config-failure"), "").unwrap();+ std::fs::remove_file(&record).unwrap();+ assert!(+ up(&podman, &root, true, BundledBots::none(), &Secrets::new())+ .unwrap_err()+ .detail+ .unwrap()+ .contains("synthetic invalid deployment override")+ );+ assert!(!std::fs::read_to_string(record).unwrap().contains(" up "));+ }+#[test]fn migrate_is_not_raised_as_a_service() {// Raised alongside the others it exits immediately, and Compose reports a service that willdiff --git a/desktop/src-tauri/tauri.conf.json b/desktop/src-tauri/tauri.conf.jsonindex 0cba16c3..6f21c796 100644--- a/desktop/src-tauri/tauri.conf.json+++ b/desktop/src-tauri/tauri.conf.json@@ -24,6 +24,17 @@},"bundle": {"active": true,+ "linux": {+ "deb": { "depends": ["pkexec", "procps", "lsof", "ca-certificates"] },+ "rpm": {+ "depends": [+ "/usr/bin/pkexec",+ "/usr/bin/ps",+ "/usr/bin/lsof",+ "ca-certificates"+ ]+ }+ },"targets": ["dmg", "nsis", "appimage", "deb", "rpm"],"icon": ["icons/32x32.png",