diff --git a/crates/tokscale-cli/src/tui/mod.rs b/crates/tokscale-cli/src/tui/mod.rs index 9ef43ba4f..5d11ac25e 100644 --- a/crates/tokscale-cli/src/tui/mod.rs +++ b/crates/tokscale-cli/src/tui/mod.rs @@ -146,6 +146,13 @@ pub fn run( return Err(e.into()); } + // From here on the TUI owns raw mode and the alternate screen for its + // whole run. Background diagnostics (e.g. cache save warnings) must not + // write raw stdio while this is set, or they corrupt the rendered + // display instead of being visible as a log line. Cleared in both + // `restore_terminal` and `restore_terminal_best_effort` below. + tokscale_core::tui_signal::set_tui_active(true); + let backend = CrosstermBackend::new(stdout); let terminal_result = Terminal::new(backend); let mut terminal = match terminal_result { @@ -233,6 +240,7 @@ pub fn run( } fn restore_terminal_best_effort() { + tokscale_core::tui_signal::set_tui_active(false); let _ = execute!( io::stdout(), LeaveAlternateScreen, @@ -243,6 +251,7 @@ fn restore_terminal_best_effort() { } fn restore_terminal(terminal: &mut Terminal>) { + tokscale_core::tui_signal::set_tui_active(false); let _ = disable_raw_mode(); let _ = execute!( terminal.backend_mut(), diff --git a/crates/tokscale-core/src/fs_atomic.rs b/crates/tokscale-core/src/fs_atomic.rs index 876c2a0b5..cfe7ae262 100644 --- a/crates/tokscale-core/src/fs_atomic.rs +++ b/crates/tokscale-core/src/fs_atomic.rs @@ -36,18 +36,41 @@ fn windows_replace_file(tmp_path: &Path, final_path: &Path) -> io::Result<()> { .collect() } + // MoveFileExW replacing an existing file is a well-known source of + // transient ERROR_ACCESS_DENIED (5) / ERROR_SHARING_VIOLATION (32) on + // Windows: antivirus, indexing, and cloud-sync agents routinely hold a + // brief scan handle open on a just-written file. Retry a handful of + // times with a short backoff before giving up, rather than surfacing a + // one-shot failure for what is usually a few-millisecond lock. + const ERROR_ACCESS_DENIED: i32 = 5; + const ERROR_SHARING_VIOLATION: i32 = 32; + const MAX_ATTEMPTS: u32 = 5; + let existing = encode(tmp_path); let new = encode(final_path); - let result = unsafe { - MoveFileExW( - existing.as_ptr(), - new.as_ptr(), - MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH, - ) - }; - if result == 0 { - Err(io::Error::last_os_error()) - } else { - Ok(()) + + for attempt in 1..=MAX_ATTEMPTS { + let result = unsafe { + MoveFileExW( + existing.as_ptr(), + new.as_ptr(), + MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH, + ) + }; + if result != 0 { + return Ok(()); + } + + let error = io::Error::last_os_error(); + let is_retryable = matches!( + error.raw_os_error(), + Some(ERROR_ACCESS_DENIED) | Some(ERROR_SHARING_VIOLATION) + ); + if !is_retryable || attempt == MAX_ATTEMPTS { + return Err(error); + } + std::thread::sleep(std::time::Duration::from_millis(10 * attempt as u64)); } + + unreachable!("loop always returns on its final attempt") } diff --git a/crates/tokscale-core/src/lib.rs b/crates/tokscale-core/src/lib.rs index f55e58258..dcf5581bd 100644 --- a/crates/tokscale-core/src/lib.rs +++ b/crates/tokscale-core/src/lib.rs @@ -15,6 +15,7 @@ mod provider_identity; pub mod scanner; pub mod sessionize; pub mod sessions; +pub mod tui_signal; pub mod wiki; pub use aggregator::*; diff --git a/crates/tokscale-core/src/message_cache.rs b/crates/tokscale-core/src/message_cache.rs index 41ebe539f..c67f61d92 100644 --- a/crates/tokscale-core/src/message_cache.rs +++ b/crates/tokscale-core/src/message_cache.rs @@ -102,10 +102,16 @@ fn warn_cache_failure_once(context: &'static str, path: &Path, error: &impl std: // Most non-TUI commands (including `submit`) do not install a tracing // subscriber. Surface persistence failures directly once per process so a - // permanently cold cache can never fail silently again. + // permanently cold cache can never fail silently again. The TUI owns raw + // mode and the alternate screen for its whole run, so a raw stdio write + // there corrupts the rendered display instead of being visible as a log + // line — suppress it in that case and rely on tracing::warn! (or the + // TUI's own status/error UI) instead. static WARNED_CONTEXTS: OnceLock>> = OnceLock::new(); let warned = WARNED_CONTEXTS.get_or_init(|| Mutex::new(HashSet::new())); - if warned.lock().is_ok_and(|mut warned| warned.insert(context)) { + if warned.lock().is_ok_and(|mut warned| warned.insert(context)) + && !crate::tui_signal::is_tui_active() + { eprintln!("tokscale: warning: {context} ({}): {error}", path.display()); } } diff --git a/crates/tokscale-core/src/pricing/lookup.rs b/crates/tokscale-core/src/pricing/lookup.rs index 2c147ec3f..203e74e97 100644 --- a/crates/tokscale-core/src/pricing/lookup.rs +++ b/crates/tokscale-core/src/pricing/lookup.rs @@ -2806,11 +2806,7 @@ mod tests { "google/gemini-3.5-flash", "Models.dev", ), - ( - "gemini-3-flash-b", - "google/gemini-3.5-flash", - "Models.dev", - ), + ("gemini-3-flash-b", "google/gemini-3.5-flash", "Models.dev"), ( // Legacy CLI responseModel for M132, the retired predecessor // of M133 — prices as the High tier, same catalog entry as diff --git a/crates/tokscale-core/src/sessions/claudecode.rs b/crates/tokscale-core/src/sessions/claudecode.rs index f52f7597f..faa441f7d 100644 --- a/crates/tokscale-core/src/sessions/claudecode.rs +++ b/crates/tokscale-core/src/sessions/claudecode.rs @@ -901,8 +901,7 @@ fn merge_claude_duplicate( // streaming chunks), so never let a later-processed duplicate // with an earlier completion timestamp shrink a duration // already established by another duplicate. - existing.duration_ms = - Some(existing.duration_ms.unwrap_or(0).max(new_duration)); + existing.duration_ms = Some(existing.duration_ms.unwrap_or(0).max(new_duration)); } } } diff --git a/crates/tokscale-core/src/tui_signal.rs b/crates/tokscale-core/src/tui_signal.rs new file mode 100644 index 000000000..f91717a6f --- /dev/null +++ b/crates/tokscale-core/src/tui_signal.rs @@ -0,0 +1,35 @@ +use std::sync::atomic::{AtomicBool, Ordering}; + +// Some diagnostics (e.g. cache save failures) fall back to a direct +// eprintln! when no tracing subscriber is guaranteed to be installed, so +// non-TUI commands still surface them. The TUI owns raw mode and the +// crossterm alternate screen for its whole lifetime, and a stray stdio +// write there corrupts the rendered display instead of being visible as a +// normal log line. This flag lets that diagnostic code suppress the raw +// stdio fallback while the TUI holds the terminal. +static TUI_ACTIVE: AtomicBool = AtomicBool::new(false); + +pub fn set_tui_active(active: bool) { + TUI_ACTIVE.store(active, Ordering::Relaxed); +} + +pub fn is_tui_active() -> bool { + TUI_ACTIVE.load(Ordering::Relaxed) +} + +#[cfg(test)] +mod tests { + use super::*; + use serial_test::serial; + + #[test] + #[serial] + fn round_trips() { + let previous = is_tui_active(); + set_tui_active(true); + assert!(is_tui_active()); + set_tui_active(false); + assert!(!is_tui_active()); + set_tui_active(previous); + } +}