Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(windows): use MoveFileExW for atomic file replacement on Windows

Steven Enamakel1f4c5b6db645
diff --git a/crates/openhuman-core/src/threads/turn_state/store.rs b/crates/openhuman-core/src/threads/turn_state/store.rs
index 94913112cf..29865a7678 100644
--- a/crates/openhuman-core/src/threads/turn_state/store.rs
+++ b/crates/openhuman-core/src/threads/turn_state/store.rs
@@ -496,20 +496,62 @@ impl TurnStateStore {
#[cfg(windows)]
fn persist_temp_file(tmp: NamedTempFile, path: &Path) -> Result<(), String> {
+ use std::os::windows::ffi::OsStrExt;
+ use windows_sys::Win32::Storage::FileSystem::{MoveFileExW, MOVEFILE_REPLACE_EXISTING};
+
let (file, temp_path) = tmp
.keep()
.map_err(|e| format!("persist turn-state file {}: {e}", path.display()))?;
// `keep` transfers ownership to us, so close the handle before replacing
// the destination and explicitly clean it up if the replacement fails.
drop(file);
- fs::rename(&temp_path, path).map_err(|e| {
+
+ let wide_path = |path: &Path| -> Result<Vec<u16>, String> {
+ let absolute = std::path::absolute(path)
+ .map_err(|e| format!("resolve turn-state path {}: {e}", path.display()))?;
+ let raw: Vec<u16> = absolute.as_os_str().encode_wide().collect();
+ let mut extended =
+ if raw.starts_with(&[b'\\' as u16, b'\\' as u16, b'?' as u16, b'\\' as u16]) {
+ raw
+ } else if raw.starts_with(&[b'\\' as u16, b'\\' as u16]) {
+ // Convert a UNC path from `\\server\share` to
+ // `\\?\UNC\server\share`.
+ let mut prefixed: Vec<u16> = r"\\?\UNC\".encode_utf16().collect();
+ prefixed.extend_from_slice(&raw[2..]);
+ prefixed
+ } else {
+ let mut prefixed: Vec<u16> = r"\\?\".encode_utf16().collect();
+ prefixed.extend_from_slice(&raw);
+ prefixed
+ };
+ extended.push(0);
+ Ok(extended)
+ };
+ let source = wide_path(&temp_path)?;
+ let destination = wide_path(path)?;
+ // SAFETY: both buffers are NUL-terminated and remain alive for the call.
+ // The paths share a directory, so this is an atomic replacement rather
+ // than a cross-volume copy-and-delete move.
+ let moved = unsafe {
+ MoveFileExW(
+ source.as_ptr(),
+ destination.as_ptr(),
+ MOVEFILE_REPLACE_EXISTING,
+ )
+ };
+ if moved != 0 {
+ return Ok(());
+ }
+
+ let error = std::io::Error::last_os_error();
+ Err({
if let Err(cleanup_err) = fs::remove_file(&temp_path) {
warn!(
"{LOG_PREFIX} failed to remove turn-state tempfile {} after rename failure: {cleanup_err}",
temp_path.display()
);
}
- format!("persist turn-state file {}: {e}", path.display())
+ format!("persist turn-state file {}: {error}", path.display())
})
}