Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(cua-spacesd): a file write on the Cua Volume mount no longer fails after the file is in place (#6322)

ddupont8c55aa4ca8b9
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/input/interactive.rs b/libs/cua-driver/rust/crates/platform-macos/src/input/interactive.rs
index e56e5174db..8976be5344 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/input/interactive.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/input/interactive.rs
@@ -374,7 +374,7 @@ impl NativeInputState {
}
fn key(&self, key: &str, state: KeyState, modifiers: &[Modifier], repeat: bool) -> Result<()> {
- let key_code = super::keyboard::key_name_to_code(key)
+ let key_code = interactive_key_code(key)
.map_err(|error| InteractiveInputError::InvalidBatch(error.to_string()))?;
let event =
CGEvent::new_keyboard_event(self.source.clone(), key_code, state == KeyState::Down)
@@ -644,6 +644,19 @@ extern "C" {
fn CGEventSetLocation(event: *mut std::ffi::c_void, x: f64, y: f64);
}
+/// Key code for a key name sent by a viewer.
+///
+/// The tool key table treats `delete` as Backspace, which is right for an
+/// agent's `press_key`. A person's live keystrokes arrive with the DOM key
+/// names, where `Delete` is forward delete and `Backspace` is its own key, so
+/// `delete` resolves to the forward-delete key here.
+fn interactive_key_code(key: &str) -> anyhow::Result<u16> {
+ if key.trim().eq_ignore_ascii_case("delete") {
+ return super::keyboard::key_name_to_code("forward_delete");
+ }
+ super::keyboard::key_name_to_code(key)
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -681,6 +694,14 @@ mod tests {
);
}
+ #[test]
+ fn a_viewers_delete_key_is_forward_delete_and_backspace_stays_backspace() {
+ assert_eq!(interactive_key_code("delete").unwrap(), 117);
+ assert_eq!(interactive_key_code("Delete").unwrap(), 117);
+ assert_eq!(interactive_key_code("backspace").unwrap(), 51);
+ assert_eq!(interactive_key_code("enter").unwrap(), 36);
+ }
+
#[test]
fn maps_native_scroll_phases() {
assert_eq!(scroll_phase_value(GesturePhase::MayBegin), 128);
diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/src/filesystem/write.rs b/libs/cua-spacesd/crates/cua-spacesd-server/src/filesystem/write.rs
index 30a75de5fc..821dcbbe18 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-server/src/filesystem/write.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-server/src/filesystem/write.rs
@@ -102,6 +102,42 @@ pub async fn prepare(target: &WriteTarget) -> Result<(), Status> {
}
}
+/// Looks-ups of a just-published file before giving up on them.
+const STAT_RETRIES: u32 = 5;
+const STAT_RETRY_WAIT: std::time::Duration = std::time::Duration::from_millis(40);
+
+/// The metadata of a file that was just renamed into place.
+///
+/// On a network mount (the Cua Volume's NFS mount on macOS) the client can
+/// answer "not found" for the new name for a moment after the rename, though
+/// the file is there. The write already succeeded, so a miss is retried a few
+/// times and then answered from the file's own metadata, rather than failing
+/// a write whose data is on disk.
+async fn stat_published<F, Fut>(
+ mut stat: F,
+ fallback: Option<std::fs::Metadata>,
+ retries: u32,
+ wait: std::time::Duration,
+) -> std::io::Result<std::fs::Metadata>
+where
+ F: FnMut() -> Fut,
+ Fut: std::future::Future<Output = std::io::Result<std::fs::Metadata>>,
+{
+ let mut attempt = 0;
+ loop {
+ match stat().await {
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
+ if attempt >= retries {
+ return fallback.ok_or(e);
+ }
+ attempt += 1;
+ tokio::time::sleep(wait).await;
+ }
+ other => return other,
+ }
+ }
+}
+
impl AtomicWriter {
/// Validates the target and opens the temporary file.
pub async fn create(target: WriteTarget) -> Result<Self, Status> {
@@ -212,6 +248,9 @@ impl AtomicWriter {
.meta("path", dest.display())
.build());
}
+ // The open file's own metadata, taken before it is renamed: what the
+ // entry reports if the destination cannot be looked up right after.
+ let published_meta = self.file.metadata().await.ok();
if let Some(tmp) = self.tmp.take() {
drop(self.file);
let published = match self.target.mode {
@@ -238,9 +277,14 @@ impl AtomicWriter {
};
published.map_err(|e| io_status(&e, &dest))?;
}
- let meta = tokio::fs::metadata(&dest)
- .await
- .map_err(|e| io_status(&e, &dest))?;
+ let meta = stat_published(
+ || tokio::fs::metadata(&dest),
+ published_meta,
+ STAT_RETRIES,
+ STAT_RETRY_WAIT,
+ )
+ .await
+ .map_err(|e| io_status(&e, &dest))?;
let mut entry = entry_info(&dest, &meta);
entry.metadata = xattr::read(&dest, &self.target.attributes.namespace, true);
Ok((entry, digest))
@@ -263,6 +307,58 @@ mod tests {
WriteTarget::new(dest, mode, 0, true)
}
+ #[tokio::test]
+ async fn a_just_published_file_that_is_not_found_yet_is_retried_then_answered() {
+ let dir = tempfile::tempdir().unwrap();
+ let real = dir.path().join("f");
+ std::fs::write(&real, b"x").unwrap();
+ let meta = std::fs::metadata(&real).unwrap();
+ let wait = std::time::Duration::from_millis(1);
+ let missing = || std::io::Error::from(std::io::ErrorKind::NotFound);
+ // A miss that clears is retried.
+ let calls = std::cell::Cell::new(0);
+ let got = stat_published(
+ || {
+ calls.set(calls.get() + 1);
+ let r = if calls.get() < 3 {
+ Err(missing())
+ } else {
+ Ok(meta.clone())
+ };
+ async move { r }
+ },
+ None,
+ 5,
+ wait,
+ )
+ .await;
+ assert!(got.is_ok());
+ assert_eq!(calls.get(), 3);
+ // A miss that stays is answered from the file's own metadata.
+ let got = stat_published(|| async { Err(missing()) }, Some(meta.clone()), 2, wait).await;
+ assert_eq!(got.unwrap().len(), 1);
+ // With nothing to fall back on, the error is still the error.
+ let got = stat_published(|| async { Err(missing()) }, None, 2, wait).await;
+ assert_eq!(got.unwrap_err().kind(), std::io::ErrorKind::NotFound);
+ // Other errors are not retried.
+ let calls = std::cell::Cell::new(0);
+ let got = stat_published(
+ || {
+ calls.set(calls.get() + 1);
+ async { Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)) }
+ },
+ Some(meta),
+ 5,
+ wait,
+ )
+ .await;
+ assert_eq!(
+ got.unwrap_err().kind(),
+ std::io::ErrorKind::PermissionDenied
+ );
+ assert_eq!(calls.get(), 1);
+ }
+
#[tokio::test]
async fn writes_atomically_and_verifies_sha() {
let dir = tempfile::tempdir().unwrap();
diff --git a/libs/cua/crates/cua-agents/src/harness.rs b/libs/cua/crates/cua-agents/src/harness.rs
index 39c50c3c87..298614787f 100644
--- a/libs/cua/crates/cua-agents/src/harness.rs
+++ b/libs/cua/crates/cua-agents/src/harness.rs
@@ -592,13 +592,36 @@ pub fn memory_dir(h: &Harness) -> Option<&'static str> {
/// (an explicit `home_dir`) keeps it in its own `.codex-sqlite` sibling.
pub fn codex_sqlite_dir(home: &str) -> String {
let home = home.trim_end_matches('/');
- let marker = "/cua-volume/agents/";
- match home.rsplit_once(marker) {
- Some((guest_home, name)) if !name.contains('/') && !name.is_empty() => {
- format!("{guest_home}/.cua/agents/codex-state/{name}")
+ // `cua-volume` in a Space; on a Mac the Volume is mounted at
+ // `~/Cua Volume`.
+ for marker in ["/cua-volume/agents/", "/Cua Volume/agents/"] {
+ if let Some((guest_home, name)) = home.rsplit_once(marker)
+ && !name.contains('/')
+ && !name.is_empty()
+ {
+ return format!("{guest_home}/.cua/agents/codex-state/{name}");
}
- _ => format!("{home}.codex-sqlite"),
}
+ format!("{home}.codex-sqlite")
+}
+
+/// Where Codex's own home (`CODEX_HOME`) lives for the agent whose home is
+/// `home`, and whether that is guest-local disk.
+///
+/// In a Space it is the home's `codex/` on the Volume. A Mac's Volume is an
+/// NFS mount that cannot make symlinks, and Codex needs them (its sign-in
+/// link, `tmp/arg0`), so there `CODEX_HOME` is guest-local
+/// (`~/.cua/agents/codex-home/<name>`) and only its `memories/` is a link
+/// into the Volume's `codex/memories`.
+pub fn codex_home_dir(home: &str) -> (String, bool) {
+ let trimmed = home.trim_end_matches('/');
+ if let Some((guest_home, name)) = trimmed.rsplit_once("/Cua Volume/agents/")
+ && !name.contains('/')
+ && !name.is_empty()
+ {
+ return (format!("{guest_home}/.cua/agents/codex-home/{name}"), true);
+ }
+ (format!("{trimmed}/codex"), false)
}
/// [`launch`] for a persistent agent whose home is the guest directory
@@ -685,7 +708,7 @@ pub fn launch_with_config(
// on; without one, a run-local CODEX_HOME holds only the provider
// override.
let codex_home = match home {
- Some(h) => Some(format!("{h}/codex")),
+ Some(h) => Some(codex_home_dir(h).0),
None => base.as_ref().map(|_| format!("{run_dir}/codex-home")),
};
let mut toml = String::new();
@@ -719,6 +742,23 @@ pub fn launch_with_config(
env(&mut l, "CODEX_SQLITE_HOME", dir);
}
if let Some(dir) = codex_home {
+ if let Some((volume_codex, local)) = home.map(|h| {
+ (
+ format!("{}/codex", h.trim_end_matches('/')),
+ codex_home_dir(h).1,
+ )
+ }) && local
+ {
+ // Memories stay on the Volume: a link from guest-local
+ // disk to the Volume's folder (the link is local, so it
+ // works where the Volume cannot make links).
+ let mem = crate::quote(&format!("{volume_codex}/memories"));
+ let link = crate::quote(&format!("{dir}/memories"));
+ l.prelude.push(format!(
+ "mkdir -p {d} {mem} && ln -sfn {mem} {link}",
+ d = crate::quote(&dir)
+ ));
+ }
let rel = match home {
Some(_) => format!("{dir}/config.toml"),
None => "codex-home/config.toml".into(),
@@ -1097,6 +1137,49 @@ mod tests {
codex_sqlite_dir("/srv/agents/ada"),
"/srv/agents/ada.codex-sqlite"
);
+ // CODEX_HOME stays on the Volume in a Space; on a Mac it is
+ // guest-local, with memories linked to the Volume.
+ assert_eq!(
+ codex_home_dir("/home/cua/cua-volume/agents/ada"),
+ ("/home/cua/cua-volume/agents/ada/codex".to_string(), false)
+ );
+ assert_eq!(
+ codex_home_dir("/Users/ada/Cua Volume/agents/codex-2"),
+ (
+ "/Users/ada/.cua/agents/codex-home/codex-2".to_string(),
+ true
+ )
+ );
+ let x = launch_with_home(
+ harness("openai-codex").unwrap(),
+ None,
+ None,
+ "/r",
+ "/w",
+ Some("/Users/ada/Cua Volume/agents/codex-2"),
+ )
+ .unwrap();
+ assert!(x.env.contains(&(
+ "CODEX_HOME".to_string(),
+ "/Users/ada/.cua/agents/codex-home/codex-2".to_string()
+ )));
+ assert_eq!(
+ x.files[0].rel,
+ "/Users/ada/.cua/agents/codex-home/codex-2/config.toml"
+ );
+ assert!(
+ x.prelude
+ .iter()
+ .any(|p| p.contains("ln -sfn")
+ && p.contains("Cua Volume/agents/codex-2/codex/memories")),
+ "{:?}",
+ x.prelude
+ );
+ // On a Mac the Volume is mounted at `~/Cua Volume`.
+ assert_eq!(
+ codex_sqlite_dir("/Users/ada/Cua Volume/agents/codex"),
+ "/Users/ada/.cua/agents/codex-state/codex"
+ );
// Not the home's own `codex/` (CODEX_HOME), which is on the Volume.
let home = "/home/cua/cua-volume/agents/ada";
assert!(!codex_sqlite_dir(home).starts_with(home));